C++ Object oriented concepts & programming

88

description

Key Points of C++

Transcript of C++ Object oriented concepts & programming

Page 1: C++ Object oriented concepts & programming
Page 2: C++ Object oriented concepts & programming
Page 3: C++ Object oriented concepts & programming

This pointer

This pointer is known as a default pointer in any function.

This pointer is basically work to receive the addresses or references for passing to called function.

We can call any function at that time calling function is receive the address using this pointer.

We can not pass any argument in function at that time this pointer is get the address.

Chapter : 3

Page 4: C++ Object oriented concepts & programming
Page 5: C++ Object oriented concepts & programming

Reference variable is known as a alias name of actual variable. It is similar to the pointer.

Reference variable is known as we can call the any function at that time we can pass the

reference of the actual variable, that time reference variable is receive the reference of the

actual variable.

We can change the any value of variable in user define function(UDF) at that time this

value is directly change in the actual variable in main function. ex.

Call by Reference in C++ Chapter : 3

Page 6: C++ Object oriented concepts & programming

C++ allows to declare any function as a inline.

Inline function is one kind of function (UDF), this function is eliminate the context

switching process.

Inline function is declare using inline keyword.

When a function is defined inside a class declaration, it is automatically made into an

inline function.

It declare before the function header.

ex.

inline <return type> class_name :: function_name(); //function header.

inline void student :: getdata();

Inline functionChapter : 3

Page 7: C++ Object oriented concepts & programming

It is possible to grant a nonmember function access to the private members of a class by using a friend.

A friend function has access to all private or protected member of the class for which it is a friend.

To declare a friend function, include its prototype within the class, preceding it with the keyword friend.

It basically used with the nonmember function.

class student

friend function Chapter : 3

Page 8: C++ Object oriented concepts & programming

In the default argument we can not pass any arguments in the

calling function at that time this function automatically takes the

default arguments.

The default argument always write after declare the normal

arguments or parameters.

Its implicitly pass the arguments.

Ex.void getdata(int x,int y,float pi=3.14); // prototype PI is default argument

In main function how to call this function

Simple si; // create class object

si.getdata(10,20);

Default argument Chapter : 3

Page 9: C++ Object oriented concepts & programming

In c language, we can pass built-in data type as a argument of any function.

The C++ provide the capability to pass whole object as a argument.

We can pass the object as a argument in any member function of the class.

We can not pass the object as a argument in any normal UDF.

Pass object as a parameter Chapter : 3

Page 10: C++ Object oriented concepts & programming
Page 11: C++ Object oriented concepts & programming

Prototyping

Prototyping is mechanism by which that define name of

function (UDF),number of arguments with datatype and

return type of the function that is like to be class.

It is declare inside class as a member function.

Ex.

return_type function_name(arguments,…);

Chapter : 3

Page 12: C++ Object oriented concepts & programming
Page 13: C++ Object oriented concepts & programming

Function Overloading

In C++ we can use the function overloading.

Function overloading is known as a we can declare same

name of function in multiple time with different arguments,

different datatype and order of arguments.

Ex.void sum(int x);

void sum(float x);

void sum(int x,int y);

void sum(int x,float y,char ch);

Chapter : 4

Page 14: C++ Object oriented concepts & programming

Static member

Static member is known as a one kind of member, it can

share common memory for all the class objects.

All the objects are access the common memory of static data

member.

Static data member declare inside class using static keyword

and it declare outside the class using scope resolution (:: )

operator.

Static data member always return the previous value.

Syntax: static <data type> variable name; //inside class

<return type> class_name :: variable name = value;

Chapter : 4

Page 15: C++ Object oriented concepts & programming

Static member function

Static member function is known as similar like a common

member function but it always access the static data

members.

It can not access the non static data members.

Static member function can‟t use the this pointer.

Static member function can not be declare virtual.

Static member function directly call using class name.

Class_name : : member function_name();

It also call using the object.

Object_name . member function_name();

Chapter : 4

Page 16: C++ Object oriented concepts & programming

Function pointer

When a program contain a large number of function to choose

from, this feature become very useful.

If the switch case statement is used instead, it will have a longer

code and is less efficient.

Such a check whether each and every function name exists.

This is done to find which function is called and then call that

function.

Instead, if the function pointer is passed, it will automatically call

the required function.

Ex. Book page no:158

Chapter : 4

Page 17: C++ Object oriented concepts & programming

Mutable data member

The mutable keyword can only be applied to non static and

non constant data members of a class. If a data member is

declare mutable then it is legal to assign a value to this data

member from a const member function.

The mutable keyword can only be applied to non static data

members of a class.

Chapter : 4

Page 18: C++ Object oriented concepts & programming

Whenever objects are passed in a function and return an object the following process is performed by compiler.

For example: Time3 = Difference (Time1, Time2);

Here Time1, Time2 & Time3 are three objects and Difference is a non member function.

The complier generated code does the following operations.

(1) Construct temporary object (for example Temp)

(2) Assign Temp the value returned by Difference function. [Time1, Time2, &Temp]

(3) Time3 = Temp

(4) delete (Temp)

Using pass by value for such objects results in inefficient as the value argument results in copying of the object to the allocated space (for the local variable) in the function and then calling the constructor to initialize, followed by a destructor call to destroy the object while returning.

This is inefficient in terms of space and time. In this case , the argument can be passed by reference to avoid unnecessary temporary copying of the object for calling the function.

Also, in this function, not how the object is returned . it is again copying of local object into the return object( a temporary object), which entails an unnecessary cost. The return can also be done by referece, so that such temporary object creation can be avoided.

If you still prefer copying the object it is fine : C++ compiler can automatically detect this and avoid this creation of temporary return object, which is know as Named Return Value optimization (NRV).

NRV is an optimization technique used by the compiler to avoid unnecessary temporary object creation and destruction while returning a struct / class object. The idea is to pass the object by address to make changes and avoid returning it as the object return requires an unnecessary object creation and destruction.

NRV optimizationChapter : 4

Page 19: C++ Object oriented concepts & programming

Mangling

When a function call made in c++ compiler it self add additional information to the function definition to differentiate function, this process is known as Mangling.

It is needed in c++ because function overloading.

Compiler internally convert every overloaded function with new name and it is known by compiler.

Linkage specification

It is a process to specified link of c language function with

c++ program.

C++ linkage is default so no need to mention explicite

specifications.

Chapter : 4

Page 20: C++ Object oriented concepts & programming

Volatile function A member function declare as a volatile if it is invoke by volatile

object.

A volatile object value can be changed by external parameter or

resource.

An object taking an input from a LANCARD does not take input

from our program.

As a when the hardware input the value related to it. Change

without our program knowledge.

Chapter : 4

Page 21: C++ Object oriented concepts & programming
Page 22: C++ Object oriented concepts & programming

Constructor

Constructor is a special member function which is having the same name of the class.

Constructor is used to initialize the member of the class.

The constructor does not have any return type specification because it does not return any value.

Constructor must be declare public visibility scope.

Constructor is automatically executed when any object of the class is define.

Constructor can not be a virtual.

Ex.Class class_name

{

data_members;

public:

class_name() //default constructor.

{

//constructor body;

}

};

There are following types of constructors.

Chapter : 7

Page 23: C++ Object oriented concepts & programming

Empty constructor

In constructor declaration we can not give any argument in

constructor declaration or we not give any statements inside

constructor this known as empty constructor.

E.x

class class_name

{

---------

public:

class_name()

{}

};

Chapter : 7

Page 24: C++ Object oriented concepts & programming

Default constructor

We can not pass any arguments or parameters in constructor declaration but we can give initialize statements inside the constructor is known as default constructor.

class class_name

{

-------

public:

class_name()

{

// statements;

}

};

There are two type of default constructors Compiler define default constructor User define default constructor.

Chapter : 7

Page 25: C++ Object oriented concepts & programming

Compiler define default constructor

When we are create object of any class and we can not declare any

default constructor in class at that time compiler call the

automatically one default constructor implicitly is known as

compiler define default constructor.

This constructor gives garbage values.

void main()

{

student s1; //s1 object call compiler default constructor

automatically.

s1.disp();

}

Chapter :7

Page 26: C++ Object oriented concepts & programming

User define default constructor

User can declare any constructor inside the class and initialize the data

member value is known as user define default constudtor, its call explicitly.

class student

{

int rno,age;

public:

student()

{

rno=0;

age=21;

}

};

Chapter : 7

Page 27: C++ Object oriented concepts & programming

Parameterized constructor

The parameterized constructor is the constructor which access

argument or parameters during the object creation.

We can pass arguments or parameters in constructor is known as

parameterized constructor.

It always required the parameters.

Chapter :7

Page 28: C++ Object oriented concepts & programming

Copy constructor

When we have a single argument containing an object reference of the same type of object to a constructor, it is known as a copy constructor.

The copy constructor is a special kind of constructor which creates a new object which is a copy of an existing one, and does it efficiently.

The copy constructor receives an object of its own class as an argument, and allows creating a new object which is copy of another without building it from scratch.

There are 3 situations in which the copy constructor is called: When we make copy of an object.

When we pass an object as an argument by value to a method.

When we return an object from a method by value.

Chapter : 7

Page 29: C++ Object oriented concepts & programming

Declaration of copy constructor.

class Test

{

string str;

public :

Test();

Test(const Test &s)

{

str = s.str;

}

};

The following are the different uses ;

// create an object which is copy of another object

Test s1("hello");

Test s2(s1); // copy constructor activated

// create an object as a copy of a temporary object

Test s3(Test("abc"));

string s4 = s1;

// object s4 does not activate the constructor, but its copy constructor to make only a copy of s1, rather than building a new object

Chapter : 7

Page 30: C++ Object oriented concepts & programming

You have to use const in the argument at the copy constructor to

create an object as a copy of a temporary object: e.g. Test(const Test

&s).

It is also possible to create a new object as copy of a different object

without using a copy constructor.

For example :

Test s4;s4.set(s1); This is an example of inefficient code. Since s4

first call its constructor to build a new object and then it make a bit-

wise copy of s1. The whole process of calling the constructor to build

an object which next is being rewritten, is wasteful, takes time and

resources. Copy constructor allows you to prevent this inefficiency.

Chapter : 7

Page 31: C++ Object oriented concepts & programming

Default copy constructor

If the programmer does not declare the copy constructor for a class, the compiler will add its own default copy constructor for the objects derived from that class.

Default copy constructor does a very simple operation, they will do a bit-wise (member-wise) copy of an object, which means that the object will be copied bit by bit.

Test s1("hello");Test s2(s1);Test s2 = s1; //the same as above

Private copy constructor

If a copy constructor is defined in a private section, the objects of the class cannot call it.

Chapter : 7

Page 32: C++ Object oriented concepts & programming

MIL(member initialization list) First initialize all member of class

The MIL is only method to initialize constant member, reference

member and object which are data member of a class.

C++ does not allows to initialize constant variable(members) and

reference member directly in declaration statements

Chapter : 7

Page 33: C++ Object oriented concepts & programming

Destructor

Destructor are usually used to deallocate memory and do other

clean up for a class object ad its class members when the object is

destroyed.

A destructor is called for a class object when that object passes out

of scope or is explicitly deleted.

A destructor is a member function with the same name as its class

prefixed bye ~ (tiled) sign.

Chapter : 7

Page 34: C++ Object oriented concepts & programming

Destructor takes no arguments and has no return type its address

can not be taken.

Destructor can not be declare const, volatile, const volatile or

static.

Destructor can be declared virtual or pure virtual.

Chapter : 6

Page 35: C++ Object oriented concepts & programming

Constructor Destructor

Constructor is used to initialize the Object. Destructor is used to destroy the object that are

created in memory previously.

Constructor can takes arguments. Destructor can not take any arguments.

Constructor overloading can be possible means more

than one constructor can be defined in same class.

Destructor overloading can not be possible.

Constructor has same name as class name. Destructor has same name as class name with tiled

operator.

Syntax of constructor:

class class_name

{

clas_sname(){}

class_name(argulist){}

} ;

Syntax of Destructor:

class class_name

{

~class-name(void){}

};

Constructor are of following:

1)Default Constructor.

2)Parameterized Constructor.

3)Copy Constructor.

Destructor has no any types.

Constructors can be used to dynamically initialize

the memory.

Destructor can be used to deallocate the memory.

Constructor indirectly use the New operator to

initialize the object.

Destructor indirectly use the Delete operator to

destroy the object initialize by constructor.

Page 36: C++ Object oriented concepts & programming

Explicit constructor

When a class contain a single parameterized constructor, there are different method to invoke this constructor function for example

Student s1(“abc”);

Student s1=“abc”;

Student s1=student(“abc”);

Student s1;S1=“abc”;

Without explicit constructor compiler will execute all three statements and in second statement automatically type casting process and convert right side data into left an side type.

Suppose in same cases we don‟t want to perform automatic type casting process while using „=„ operator at that time a constructor is declare as a explicitly.

Chapter : 7

Page 37: C++ Object oriented concepts & programming

Chapter : 7

Page 38: C++ Object oriented concepts & programming
Page 39: C++ Object oriented concepts & programming

Operator overloading

It is the process which gives additional meaning to an existing

operator.

To overloading any operator, we require to define a overload function

of an operator in a class.

An operator function can be declared as a member function or friend

function of a class.

An overload function can not be declared as a non member function.

An operator function declare with the “operator” keyword.

Page 40: C++ Object oriented concepts & programming

Operator overloading is a process which implements an existing

operator with new meaning in user define data type like class.

Operator are overloaded as a function.

The main advantage of operator overloading concept in C++ is to

make program more readable.

For implementing operator overloading concept, we can be define

operator function either as member function (non static) or friend

function.

The different is that a friend function will have only one argument for

unary operator(++,--) and two for binary operators (+,-,*,/,%).

While member function has no arguments for unary operator and

only one for binary operator. This is because the object used to invoke

the member function is passed implicitly and therefore is available for

the member function using the pointer.

Page 41: C++ Object oriented concepts & programming

We can not overload this operators

Class member access operator ( . .*);

Scope resolution operator ( : : )

Size of operator (sizeof)

Condition operator ( ? : )

Casting operator

# and ## tokens for macro preprocessors.

Page 42: C++ Object oriented concepts & programming

Rules for operator overloading

Only existing operator can be overloaded. New operators cannot

be overloaded e.g. **

The overloaded operator must have at least one operand that is of

user defined type.

We can not change the basic meaning of an operator. That is to say,

we can not redefine the plus(+) operator to subtract one value

from the other.

Overloaded operator follow the syntax rules of the original

operators. They can not be overridden.

we can not use friend function to overload certain operator like

new & delete. Only member function is used to overload this type

of operator.

Page 43: C++ Object oriented concepts & programming

Binary operators declared as member functions take one

argument; if declared as friend functions, they take two

arguments.

Overloaded operators cannot have default arguments.

All overloaded operators except assignment ( = operator)

are inherited by derived class.

Page 44: C++ Object oriented concepts & programming

There are following operators can be overloaded

+ - * / % ^

~ ! , = < >

& <= >= | ++ --

<< >> == != && ||

+= -= *= /= %= ^=

&= |= <<= >>= [ ] ( )

-> ->* New New[ ] Delete Delete[ ]

Page 45: C++ Object oriented concepts & programming

User define conversion/type conversion

we know that when constants and variable of different types are

mixed in an expression, c language applies automatic type

conversion to the operands as per certain rules.

Similarly as assignment operation also cause a the automatic type

conversion.

The type of automatic converted to the type of the variable on the

left side.

E.g. int m;

float x=3.14;

m=x;

Page 46: C++ Object oriented concepts & programming

Similarly in user define type or object, we can easily add two object

of same class but if we want to add two different type of object then

it is not directly possible.

Since the user-define data type are designed by us to suit our

requirements, the compiler does not support automatic type

conversion for such data types.

To solve this problem, we need to write our own conversion routine

to guide the compiler what to do when such assignments are

provided.

Page 47: C++ Object oriented concepts & programming

Type of conversions:

Built-in data type to object (UDT)

Object (UDT) to built-in data type

Wrapper class

From one object to another type of object.

Page 48: C++ Object oriented concepts & programming

Built-in data type to object (UDT)

This is problem is solved with the help of constructor.

For example: student s1[10] takes an arguments of built in data type

and convert to a student type of an object.

Whenever we use constructor to initialize attribute, we convert the

argument type to the native object type for the constructor.

Ex.

Page 49: C++ Object oriented concepts & programming

Object (UDT) to built-in data type

The constructor did a good job in type conversion from a basic type to class

type.

What about the conversion from a class to basic type ? The constructor

function do not support this operation. For that C++ allows us to define an

overloaded casting operator that could be used to convert a class type to a

basic type.

It is also know as conversion function.

Syntax: this function converts a class type data to type name.

operator typename()

{

function statements;

}

Page 50: C++ Object oriented concepts & programming
Page 51: C++ Object oriented concepts & programming

For example:

The operator double () converts a class object to type double, similar

operator int () converts a class type to integer type and so on.

The casting operator function should satisfy the following conditions.

It must be a class member

It must not specify a return type

It must not have any arguments.

Page 52: C++ Object oriented concepts & programming

Wrapper class

Some of built in type are not objects, eg. Int, char etc. however, for

complete object orientation, they should be objects, for instance, if we

want to have an integer class, we can specify functions for reading integer

with proper validation checks.

If they are define as a class, we can inherits them to have our own class.

A class that provides a basic data type with some additional facilities is

known as a wrapper classes.

Some times we may need to covert the wrapper class object into built in

type objects and vice versa.

Converting from built in type to wrapper class is possible using

constructors and the inverse is possible using conversion operators.

When we need to convert from a built in type object to a user defined

object, we use constructors.

Page 53: C++ Object oriented concepts & programming
Page 54: C++ Object oriented concepts & programming

From one object to another type of object

In some cases we would like to convert one class type data to another

class type.eg. Obj1 = Obje2

Here obj1 is an object of class x and obj2 is an object of class y. both

are different classes objects.

Since conversion takes place from, class y to class x, class y is known

as source class and class x is known as the destination class.

Such conversion between objects of different classes can be carried

out by either a constructor or a conversion function (operator

function).

Page 55: C++ Object oriented concepts & programming

Using constructor method.

Page 56: C++ Object oriented concepts & programming
Page 57: C++ Object oriented concepts & programming

Using conversion function.

Page 58: C++ Object oriented concepts & programming
Page 59: C++ Object oriented concepts & programming
Page 60: C++ Object oriented concepts & programming

The mechanism of creating a new class from a base class or

existing class is called a inheritance.

An existing class is known as a “base class” and new class is known

as a “derived class”.

Derived class contains all features of base class and also contain a

all feature of own class.

There are different type of inheritance.

Page 61: C++ Object oriented concepts & programming

Type of Inheritance

1) single inheritance : A class is derived from single base class is called single inheritance.

2)Multiple inheritance: A one base class derived from more than one derived class is known as

multiple inheritance.

3)Hierarchical inheritance: Many base classes are derived from one derived class is known as

hierarchical inheritance.

4)Multi level inheritance. The mechanism of derived class from another derived class is known as

multilevel inheritance.

5)Hybrid inheritance. In this one base class is derived from more than one derive class and there

many derived classes are derived from one derived class is known as hybrid inheritance.

Page 62: C++ Object oriented concepts & programming

How to inherit base class into derived class.

<identifier> derived class_name : <access specifire> base class_name

{

}

Access specifires like, ………… private, public and protected

Ex.

class A

{

}

class B:public A

{

}

Page 63: C++ Object oriented concepts & programming

Different form of Inheritance.

Page 64: C++ Object oriented concepts & programming

Derivations:

Private:

Public:

Protected:

Page 65: C++ Object oriented concepts & programming

Effect of access specifier in further derivation.

1. If the access specifier is public:

1. The effective specifier in the derivation class is the same as base class(public

remain public and protected remain protected in derived class).

2. if we inherit further as a public, they are again going to retain same access

specifier. So public in base class is also public in derived class.

2. If access specifier is protected:

1. The access specifier in derived class is protected in both for public and

protected members of base class.

2. In further derivation as public then it doesn‟t make public members of base

class as a public but instead it threaded as protected.

The most important difference between a member of the class derived as

protected and as a private.

if privately derived then member is not available for further inheritance,

inheritance, in case of protected it is available for further inheritance.

Page 66: C++ Object oriented concepts & programming

Single inheritance.

Page 67: C++ Object oriented concepts & programming
Page 68: C++ Object oriented concepts & programming
Page 69: C++ Object oriented concepts & programming

Multiple inheritance

Page 70: C++ Object oriented concepts & programming
Page 71: C++ Object oriented concepts & programming
Page 72: C++ Object oriented concepts & programming
Page 73: C++ Object oriented concepts & programming

Hierarchical inheritance

Page 74: C++ Object oriented concepts & programming
Page 75: C++ Object oriented concepts & programming

Multilevel inheritance

Page 76: C++ Object oriented concepts & programming
Page 77: C++ Object oriented concepts & programming

Hybrid inheritance

Page 78: C++ Object oriented concepts & programming
Page 79: C++ Object oriented concepts & programming

Introduction of Access Control

The member function of the class, member function of the derived

class, friend and object can access different part of the class.

Access for public, private and protected members is different for all

entities.

Access control describe who can access what and in which form.

Available or accessible entities can be determined bye the access

control. Three entities available for access are public, private and

protected.

Page 80: C++ Object oriented concepts & programming

Introduction of Access Declaration

If we derived a class in private way, we will not be able to access data

members of the base class members using derives class objects.

If we derived in a public way, all members will be accessed as public.

If we want to derive a class and want only a few and not all of the

public members to be available to objects of the derived class, then

we have to provide access declaration.

Using access declaration, we can provide public access to some of the

base class members even after deriving them as private.

Ex.

Page 81: C++ Object oriented concepts & programming
Page 82: C++ Object oriented concepts & programming
Page 83: C++ Object oriented concepts & programming

Virtual Base Class

If we think about hybrid inheritance. Suppose there is a class base

class A from which we derive two different classes B & C.

We may derive a new class D from B & C classes, then are two

copies of base class A now copies in D class, one from B and second

from C.

It is diagrammatically shown in figure.

Page 84: C++ Object oriented concepts & programming

We have two different copies of all members of base class

elements. This has two distinct problems,

The first problem is the code size increase, which is very obvious.

The second problem is how to access a member class object from a

further derived class,. We obviously need the scope resolution

operator.

In such a case compiler would get confused between two base class

members.

Having two different copies and need for qualifying with a base

class name is a serious problem in some case.

To solve this problem we have to precede the first derivation by

keyword virtual.

Page 85: C++ Object oriented concepts & programming

We can write virtual public or public virtual.

The compiler would consider both the definition the same

way. Whenever compiler finds virtual keyword with

derivation, it would ensure that two instance of the same

base class are not inheritance into the class derived from the

derived class of base.

We have a single instance in class D, this is the advantage of

virtual base classes.

Page 86: C++ Object oriented concepts & programming

Abstract Base Class.

The classes without any object are known as abstract classes,

A class that contains at least one pure virtual function is said

to be abstract.

An abstract class contain one or more function for which

there is no definition ( that is, a pure virtual function) , no

objects pointers and references to an abstract class, this

allows abstract classes to support run-time polymorphism,

which relies upon base-class pointers and references to select

the proper virtual function.

Page 87: C++ Object oriented concepts & programming
Page 88: C++ Object oriented concepts & programming