Oosd Unit - 5

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

Accessing Class Members: The main () cannot contain statements that access class members directly.

Class members can be


accessed only by an object of that class. To access class members, use the dot (.) operator. The dot operator links the name of
an object with the name of a member. The general form of the dot operator is shown here:
Object_name.member_name;
Example
ob1.set_a(10);
C++ program to find sum of two numbers using classes.
#include <iostream>
using namespace std;
class A
{
int a,b,c;
public:
void sum()
{
cout<<"enter two numbers for sum";
cin>>a>>b;
c=a+b;
cout<<"sum="<<c;
}
void multi();
};
void A :: multi()
{
int a,b,c;
cout<<"\n enter two numbers for multiplication";
cin>>a>>b;
c=a*b;
cout<<"Multiplication="<<c;
}
int main()
{
A u;
u.sum();
u.multi();
return(0);
}
3. Scope Resolution operator
Member functions can be defined within the class definition or separately using scope resolution operator (::). Defining a
member function within the class definition declares the function inline, even if you do not use the inline specifier. Defining a
member function using scope resolution operator uses following declaration.
return-type class-name::func-name(parameter- list)
{
// body of function
}
Here the class-name is the name of the class to which the function belongs. The scope resolution operator (::) tells the compiler
that the function func-name belongs to the class class-name. That is, the scope of the function is restricted to the class-name
specified.
2
Another use of scope resolution operator is to allow access to the global version of a variable. In many situation, it happens
that the name of global variable and the name of the local variable are same .In this while accessing the variable, the priority is
given to the local variable by the compiler. If we want to access or use the global variable, then the scope resolution operator
(::) is used. The syntax for accessing a global variable using scope resolution operator is as follows:-
:: Global-variable-name
#include <iostream>
using namespace std;
char c = 'a'; // global variable
int main()
{
char c = 'b'; //local variable
cout << "Local variable: " << c << "\n";
cout << "Global variable: " << ::c << "\n"; //using scope resolution operator
return 0;
}
4. Static data members: When we declare a normal variable (data member) in a class, different copies of those data
members create with the associated objects. In some cases when we need a common data member that should be same for
all objects, we cannot do this using normal data members. To fulfill such cases, we need static data members.
Static data member is a variable which is declared with the static keyword, it is also known as class member, thus only single
copy of the variable creates for all objects. Any changes in the static data member through one member function will reflect
in all other object’s member functions.
One use of a static member variable is to provide access control to some shared resource used by all objects of a class.
Another interesting use of a static member variable is to keep track of the number of objects of a particular class type that are
in existence.
Declaration
static data_type member_name;
If you are calling a static data member within a member function, member function should be declared as static (i.e. a static
member function can access the static data members).
Static Data member has the following properties:
I. It is initialized by zero when first object of class is created.
II. Only one copy of static data member is created for the entire class and all object share the same copy.
III. Its scope is within class but its lifetime is entire program.
IV. They are used to store the values that are common for all the objects.
5. Static Member Functions
Member functions may also be declared as static. They may only directly refer to other static members of the class. Actually,
static member functions have limited applications, but one good use for them is to "preinitialize" private static data before any
object is actually created. A static function can be access only by other static data member (variables) and function declared in
the class. A static member function can be called using the class name instead of its objects as follows:
class name :: function name
Note: Inline function can never be static.
#include <iostream> #include <iostream>
using namespace std; using namespace std;
class Demo class MyClass
{ {
private: int simple; // Simple variable
static int X,Y; //static data members static int counter; // Static data member or variable
public: public :
static void Print() //static member function void inc( ) ; // to increment value of ‘counter’
{ void print( ) ; // print value of ‘counter’
3
cout <<"Value of X: " << X << endl; };
cout <<"Value of Y: " << Y << endl; int MyClass :: counter = 0; // Definition of static variable
} void MyClass :: inc()
}; {
int Demo :: X =10; //static data members counter++ ;
initializations simple++ ;
int Demo :: Y =20; }
int main() void MyClass :: print()
{ {
Demo OB; cout<< "\n Counter is : " << counter ;
cout<<"Printing through object name:"<<endl; }
OB.Print(); //accessing class name with object name int main()
cout<<"Printing through class name:"<<endl; {
Demo::Print(); //accessing class name with class name MyClass a1; // count = 0, simple= garbage
return 0; a1.inc( ); // count = 1, simple = garbage + 1
} a1.print( ) ;
Output: Printing through object name: MyClass a2; // no new counter, new simple, simple = new
Value of X: 10 garbage
Value of Y: 20 a2.inc( ); // count = 2, simple = new garbage + 1
Printing through class name: a2.print( );
Value of X: 10 return 0;
Value of Y: 20 }

6. Constructor:
A constructor is a special member function of a class whose task is to initializes objects of a class. It is special because its name
is the same name as the class name. In C++, Constructor is automatically called when object (instance of class) created. It is
called constructor because it constructs the values of data members of the class.
A constructor is different from normal functions in following ways:
• Constructor has same name as the class itself.
• They should be declared in the public section.
• Constructors cannot be virtual.
• Constructors don’t have return type, not even void.
• They cannot be inherited, though a derived class can call the base class constructor.
• A constructor is automatically called when an object is created.
• They make „implicit calls‟ to the operators new and delete when memory allocation is required.
• If we do not specify a constructor, C++ compiler generates a default constructor for us (expects no parameters and
has an empty body).
Program for describing the constructor
#include <iostream>
using namespace std;
class Example
{
int a, b; // Variable Declaration
public:
//Constructor
Example()
{
a = 10; // Assign Values In Constructor
b = 20;
cout << "I am Constructor\n";

4
}
void Display()
{
cout << "Values :" << a << "\t" << b;
}
};
int main() {
Example Object;
// Constructor invoked.
Object.Display();
return 0;
}
Output: I am Constructor
Values : 10 20
Constructor vs Member function
Now that we know what is constructor, lets discuss how a constructor is different from member function of the class.
1) Constructor doesn’t have a return type. Member function has a return type.
2) Constructor is automatically called when we create the object of the class. Member function needs to be called
explicitly using object of class.
3) When we do not create any constructor in our class, C++ compiler generates a default constructor and insert it into our
code. The same does not apply to member functions.
Types of Constructor:
• Default Constructor
• Parameterized Constructor
• Copy Constructor
The constructor is considered to be default one if it does not have any arguments or it has arguments, but all the arguments
have default values. If we do not define a constructor explicitly, the compiler will provide a default constructor implicitly.
For example: previous example.
#include <iostream> #include <iostream>
using namespace std; using namespace std;
class Cube class Cube
{ {
public: public:
int side; int side;
Cube() };
{ int main()
side = 10; {
} Cube c;
}; cout <<"\n Value is :"<< c.side;
int main() return 0;
{ }
Cube c; Output : Value is : 0 or any random value
(In the case, default constructor provided by the compiler will be
cout << c.side; called which will initialize the object data members to default
return 0; value, which will be 0 in this case.)
} Output: 10

5
A constructor which has parameters is called parameterized constructor. It is used to provide different values to distinct
objects.
#include <iostream>
using namespace std;
class ABC {
private:
int length,breadth,x;
public:
ABC (int a,int b) //parameterized constructor to initialize a and b
{ length = a;
breadth = b; }
ABC (int a) //parameterized constructor to initialize a
{ cout << "One Parameter = " << a << endl;
length = breadth = a; }
int area( ) //function to find area
{ x = length * breadth;
return x; }
void display( ) //function to display the area
{ cout << "Area = " << x << endl; }
};
int main()
{ ABC b(6);
b.area();
b.display();
ABC c(2,4); //initializing the data members of object 'c' implicitly
c.area();
c.display();
ABC c1= ABC(4,4); // initializing the data members of object 'c' explicitly
c1.area();
c1.display();
return 0;
} Output: One Parameter = 6
Area = 36
Area = 8
Area = 16
program
using namespace std;
class ABC
{
private:
int length,breadth,x;
public:
ABC (int a=20,int b=4) //parameterized constructor to initialize l and b
{
6
length = a;
breadth = b;
}
int area( ) //function to find area
{
x = length * breadth;
return x;
}
void display( ) //function to display the area
{
cout << "Area = " << x << endl;
}
};
int main()
{
ABC c; //initializing the data members of object 'c' implicitly
c.area();
c.display();
return 0;
}

A copy constructor is the member function which initializes an object using another object of the same class. A Copy constructor
is the overloaded constructor used to declare and initialize an object from another object of the same class. A Copy Constructor
is the type of constructor which is used to create the copy of the already existing object of the class type.
A prototype of the copy constructor
class_name (const class_name & old_object);
The copy constructor argument should be const because we don’t want the values of old objects to be modified inside the
body of this constructor.
Definition of Copy constructor
class class_name
{
public:
class_name(class_name & obj)
{
// Copy Constructor code
}
//... other Variables & Functions
}
Syntax: Copy Constructor calling In Main Function
Method 1 - Copy Constructor
class_name object2(object1);
Method 2 - Copy Constrcutor
class_name object2 = object1;
When is copy constructor called?
1. When a function returns the object of the class.
2. When the object of the class is passed as an argument to a function.
3. When we are creating an object of a class based on another object of the same class.
7
#include <iostream> #include <iostream>
using namespace std; using namespace std;
class sample class A
{ {
int n; int x, y;
public: public:
sample() A()
{ {
n=0; cout << "Default constructor called!";
} }
sample(int a) A(int a, int b)
{ {
n=a; cout << "Parametrized Constructor called!\n";
} x = a;
sample(sample &x) y = b;
{ }
n=x.n; A(const A &old)
} {
void display() // old is the old object being passed
{ x = old.x; //This object's x to old object's x
cout<<n<<”\n”; y = old.y;
} cout << "Copy Constructor called!\n";
}; }
int main() void print()
{ {
sample A(100); cout << x << " " << y << "\n";
sample B(A); }
sample C=A; };
sample D; int main()
D=A; { // Sample Code to show default constructor
A.display(); A obj(10, 20); // making a object of class A -- >Implicit
B.display(); A obj2(obj); // Copy Constructor called old object 'obj' is passed
C.display(); obj2.print();
D.display(); return 0;
return 0; }
} Output: Parametrized Constructor called!
Output: 100 100 100 100 Copy Constructor called!
10 20

7. Destructor
C++ destructor is a special member function that is executed automatically when an object goes out of scope or is destroyed
that has been created by the constructor. C++ destructors are used to de-allocate the memory that has been allocated for the
object by the constructor. Its syntax is same as constructor except the fact that it is preceded by the tilde sign.
class class_name
{
public:
class_name(); //constructor.
~class_name(); //destructor.
};
Important points:
1. Destructor can’t be overloaded or inheritance.
2. Destructor neither takes any arguments nor does it return value.
3. Destructor called when you call the delete operator.
8
4. In C# and Java the allocation and release of memory allocated to objects are implicitly handled by the garbage collector.
5. A destructor function is called automatically when the object goes out of scope:
I. the function ends
II. the program ends
III. a block containing local variables ends
IV. a delete operator is called
6. There can only one destructor in a class.
7. In fact, it is always a good idea to make destructors virtual in base class when we have a virtual function.
8. Recovering the heap space allocated during the lifetime of an object.
9. Constructors are called in order of derivation, destructors in reverse order.
Example
#include <iostream> #include <iostream>
using namespace std; using namespace std;
class Marks class Rectangle
{ {
public: int length;
Int maths; int breadth;
Int science; public:
Marks() //constructor void setDimension(int l, int b)
{ {
cout << "Inside Constructor"<<endl; length = l;
cout << "C++ Object created"<<endl; breadth = b;
} }
~Marks() //Destructor int getArea()
{ {
cout << "Inside Destructor"<<endl; return length * breadth;
cout << "C++ Object destructed"<<endl; }
} Rectangle() // Constructor
}; {
int main( ) cout << "Constructor" << endl;
{ }
Marks m1; ~Rectangle() // Destructor
Marks m2; {
return 0; cout << "Destructor" << endl;
} }
};
int main()
{
Rectangle rt;
rt.setDimension(7, 4);
cout << rt.getArea() << endl;
return 0;
}
Output: Inside Constructor Output:
C++ Object created Constructor
Inside Constructor 28
C++ Object created Destructor
Inside Destructor
C++ Object destructed
Inside Destructor
C++ Object destructed

8. Operator overloading

9
Operator overloading is a compile-time polymorphism in which the operator is overloaded to provide the special meaning to
the user-defined data type. Operator overloading is used to redefines most of the operators available in C++. It is used to
perform the operation on the user-defined data type. For example, ‘+' operator can be overloaded to perform addition on
various user define data types, like for Integer, String (concatenation) etc.
The advantage of Operators overloading is to perform different operations on the same operand.
Operators that cannot be overloaded are as follows:
o Scope operator (::)
o Sizeof
o Member selector (.)
o member pointer selector(*)
o Ternary operator (? :)
Operator Overloading Syntax:

Implementing Operator Overloading in C++


Operator overloading can be done by implementing a function which can be :
1. Member Function
2. Non-Member Function
3. Friend Function
Operator overloading function can be a member function if the Left operand is an Object of that class, but if the Left operand
is different, then Operator overloading function must be a non-member function.
Operator overloading function can be made friend function if it needs access to the private and protected members of class.
Restrictions on Operator Overloading in C++
Following are some restrictions to be kept in mind while implementing operator overloading.
1. Precedence and Associativity of an operator cannot be changed.
2. Arity (numbers of Operands) cannot be changed. Unary operator remains unary, binary remains binary etc.
3. No new operators can be created, only existing operators can be overloaded.
4. Declare the operator function in the public part of the class.
5. Cannot redefine the meaning of a procedure. You cannot change how integers are added.
The number of arguments in the overloaded operator’s arguments list depends
1. Operator function must be either member function or friend function.
2. If operator function is a friend function then it will have one argument for unary operator & two arguments for binary
operator.
3. If operator function is a member function then it will have Zero argument for unary operator & one argument for binary
operator.

#include <iostream> #include<iostream>


using namespace std; using namespace std;
class MinusOverload class Box {
{ public:
private: double getVolume(void)
int a,b; {
public: return length * breadth * height;
void Distance() }
{ void setLength( double len, double bre, double hei )
10
a = 0; {
b = 0; length = len;
} breadth = bre;
MinusOverload(int f, int i) height = hei;
{ }
int c; // Overload + operator to add two Box objects.
a = f; Box operator+(const Box& b)
b = i; {
c = a - b; Box box;
cout << "\nC:" << c; box.length = length + b.length;
} box.breadth = breadth + b.breadth;
void display() box.height = height + b.height;
{ return box;
cout << "A: " << a << " B:" << b << endl; }
} private:
MinusOverload operator-() double length; // Length of a box
{ double breadth; // Breadth of a box
a = -a; double height; // Height of a box
b = -b; };
return MinusOverload(a, b); int main() {
} Box Box1,Box2,Box3;
}; double volume = 0.0; // Store the volume of a box here
int main() Box1.setLength(6.0,7.0,5.0);
{ Box2.setLength(12.0,13.0,10.0);
MinusOverload M1(6, 8), M2(-3, -4); volume = Box1.getVolume();
-M1; //M1.operator-(); cout << "Volume of Box1 : " << volume <<endl;
M1.display(); volume = Box2.getVolume();
-M2; cout << "Volume of Box2 : " << volume <<endl;
M2.display(); Box3 = Box1 + Box2; //also used as Box3=Box1.operator+(Box2)
return 0; volume = Box3.getVolume();
} cout << "Volume of Box3 : " << volume <<endl;
Output: return 0;
C:-2 }
C:1 Output:
C:2 A: -6 B:-8 Volume of Box1 : 210
C:-1 A: 3 B:4 Volume of Box2 : 1560
Volume of Box3 : 5400
Simple Program
#include <iostream>
using namespace std;
class A {
int x;
public:
A(int i){ x=i; }
void operator+(A); };
void A :: operator+(A a)
{ int m = x+a.x;
cout<<"The result of the addition of two objects is : "<<m; }
int main()
{ A a1(5);
A a2(4);
a1+a2; //a1.operator+(a2);
return 0;
}

9. Inheritance:
11
Inheritance is the process by which one object can acquire the properties of another. When one class is inherited by another,
the class that is inherited is called the base class. The inheriting class is called the derived (child) class. When the class child,
inherits the class parent, the class child is referred to as derived class (sub class) and the class parent as a base class (super
class). In this case, the class child has two parts: a derived part and an incremental part. The derived part is inherited from the
class parent. The incremental part is the new code written specifically for the class child.
A derived class can be defined by specifying its relationship with the base class in addition to its own details.
class derived-class-name : visibility-mode base-class-name
{
………
………
}
The colon indicates that the derived class name is derived from the base class-name. The visibility mode is optional and if
present, may be either private or protected or public. The default is private. Visibility mode specifies whether the features of
the base class are privately derived or publicly derived.
Example
Consider a group of vehicles. You need to create classes for Bus, Car and Truck. The methods fuelAmount (), capacity (),
applyBrakes () will be same for all of the three classes. This is how the above task would look like without using inheritance in
C++:

You can clearly see that above process results in duplication of same code 3 times. This increases the chances of error and data
redundancy. To avoid this type of situation, inheritance is used. If we create a class Vehicle and write these three functions in
it and inherit the rest of the classes from the vehicle class, then we can simply avoid the duplication of data and increase re-
usability. Look at the below diagram in which the three classes are inherited from vehicle class:

Importance of Inheritance in C++


There are numerous reasons as to why the concept of inheritance was introduced in C++. Here are some of the reasons why:
o It drastically reduces code redundancy.
o Inheritance in C++ offers the feature of code reusability.
o It increases the code reliability by providing a definite body to the program.
o The transitive nature of inheritance makes things much easier for us.
class A {
public:
int x;
protected:
int y;
private: Visibility of inheritance
int z;
};

12
class B : public A When the access specifier for a base class is public, all public members of the base
{ become public members of the derived class, and all protected members of the
// x is public base become protected members of the derived class. In all cases, the base's
// y is protected
private elements remain private to the base and are not accessible by members
// z is not accessible from B
}; of the derived class.
class C : protected A When the access specifier for a base class is protected, all public and protected
{ members of the base become protected members of the derived class.
// x is protected Both members of the base class can only be accessed by the member functions
// y is protected of the derived class. Private members of base class are inaccessible to the
// z is not accessible from C objects of the derived class.
};

class D : private A // 'private' is default When a base class' access specifier is private, public and protected members of
for classes the base become private members of the derived class. This means that they are
{ still accessible by members of the derived class.
// x is private Private members of base class are inaccessible to the objects of the derived class
// y is private
// z is not accessible from D
};
For example, This concepts is illustrated in the following program.
#include <iostream> #include <iostream> #include <iostream>
using namespace std; using namespace std; using namespace std;
class base { class base { class A{
int i, j; protected: private:
public: int i, j; // private to base, but accessible int a;
void set(int a, int b) by derived protected:
{ i=a; j=b; } public: int x; //can access by the derived
void show() void setij(int a, int b) { i=a; j=b; } class
{ cout << i << " " << j << "\n"; } void showij() { cout << i << " " << j << "\n"; public:
}; } void setVal(int v)
class derived : public base { }; { x=v; }
int k; class derived : protected base{ };
public: int k; class B:private A {
derived(int x) { k=x; } public: public:
void showk() // derived may access base's i and j and void printVal(void)
{ cout << k << "\n"; } setij(). {
}; void setk() { setij(10, 12); k = i*j; } setVal(10); //accessing public
int main() // may access showij() here member function here
{ void showall() { cout << k << " "; showij(); } //protected data member direct access here
derived ob(3); }; cout << "value of x: " << x << endl;
ob.set(1, 2); // access member of base int main() }
ob.show(); // access member of base { };
ob.showk(); // uses member of derived derived ob; int main()
class // ob.setij(2, 3); // illegal, setij() is {
return 0; // protected member of derived B objB;
} ob.setk(); // OK, public member of derived objB.printVal();
Output: 1 2 ob.showall(); // OK, public member of derived return 0;
3 // ob.showij(); // illegal, showij() is protected }
// member of derived
return 0;
}

Types of Inheritance in C++


• Single inheritance
• Multilevel inheritance
• Multiple inheritance

13
• Hierarchical inheritance
• Hybrid inheritance

 Single Inheritance: In single inheritance one class inherits one class exactly. This is the simplest form of inheritance.

Syntax:
class subclass_name: access_mode base_class
{
//body of subclass
};
 Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can inherit from more than one classes.
i.e one sub class is inherited from more than one base classes.
Syntax:
class subclass_name : access_mode base_class1, access_mode base_class2, ....
{
//body of subclass
};

#include <iostream>
using namespace std;
class stud {
protected:
int roll, m1, m2;
public:
void get()
{
cout << "Enter the Roll No.: "; cin >> roll;
cout << "Enter the two highest marks: "; cin >> m1 >> m2;
}
};
class extracurriculam {
protected:
int xm;
public:
void getsm()
{
cout << "\nEnter the mark for Extra Curriculam Activities: "; cin >> xm;
}
};
class output : public stud, public extracurriculam {
int tot, avg;
public:
void display()
{
tot = (m1 + m2 + xm);
avg = tot / 3;
cout << "\n\n\tRoll No : " << roll << "\n\tTotal : " << tot;
cout << "\n\tAverage : " << avg;
}
};
int main()
{ output O;
O.get();
O.getsm();
14
O.display();
}  Multilevel
Inheritance: In
this type of inheritance, a derived class is created from another derived class.
Syntax:
class subclass_name1 : access_mode base_class
{
//body of subclass
};
class subclass_name2 : access_mode subclass_name1
{
//body of subclass
};
#include <iostream>
using namespace std;
class base
{
public:
int x;
void getdata()
{ cout << "Enter value of x= "; cin >> x;}
void show()
{ cout<<"Entered values are :"<<x;}
};
class derive1 : public base
{
public:
int y;
void readdata()
{ base :: getdata();
cout << "\nEnter value of y= "; cin >> y; }
void show1()
{ cout<<" ,\t"<<y;}
};
class derive2 : public derive1
{
private:
int z;
public:
void indata()
{ derive1 :: readdata();
cout << "\nEnter value of z= "; cin >> z; }
void show2()
{ cout<<" ,\t"<<z;}
void product()
{ cout << "\nProduct= " << x * y * z; }
};
15
int main() Output:
{ derive2 a; Enter value of x=3
a.indata(); Enter value of y=5
Enter value of z=7
a.show();
Entered value are :3, 5, 7
a.show1(); Product = 105
a.show2();
a.product();
return 0;
}

 Hierarchical Inheritance: In this type of inheritance, more than one sub class is inherited from a single base class. i.e.
more than one derived class is created from a single base class.
Syntax:
class Vehicle
{
//body of class
};
class Car: public Vehicle
{
//body of first subclass
};
class Bus: public Vehicle
{
//body of second subclass
};

#include <iostream>
using namespace std;
class A
{public:
int x, y;
void getdata()
{cout << "\nEnter value of x and y:\n"; cin >> x >> y;}
};
class B : public A
{public:
void product()
{cout << "\nProduct= " << x * y; }
};
class C : public A
{public:
//A :: getdata(); show error because it is not friend fun

16
void sum()
{ A :: getdata();
cout << "\nSum= " << x + y;}
}; Output:
int main() Enter value of x and y:
{ B obj1; 3
8
C obj2;
Product= 24
obj1.getdata(); Enter value of x and y:
obj1.product(); 7
obj2.sum(); 4
Sum=11
return 0;
 Hybrid (Virtual)
} Inheritance:
Hybrid Inheritance is implemented by combining more than one type of inheritance. For
example: Combining Hierarchical inheritance and Multiple Inheritance. Below shows the combination of hierarchical and
multiple inheritance:

#include <iostream>
using namespace std;
class stu{
int id;
char name[20];
public:
void getstu(){
cout << "Enter stuid, name";
cin >> id >> name;
}
};
class marks: public stu{
protected:
17
int m, p, c;
public:
void getmarks(){
cout << "Enter 3 subject marks:";
cin >> m >> p >> c;
}
};
class sports{
protected:
int spmarks;
public:
void getsports(){
cout << "Enter sports marks:";
cin >> spmarks;
}
};
class result : public marks, public sports{
int tot;
float avg;
public :
void show(){
marks :: getmarks();
sports :: getsports();
tot=m+p+c;
avg=tot/3;
cout<<"Total=" << tot << endl;
cout<<"Average=" << avg << endl;
cout<<"Average + Sports marks =" << avg+spmarks;
}
};
Output:
int main(){ Enter stuid, name 56
abc
result r; Enter 3 subject marks:12
r.getstu(); 13
//r.getmarks(); 14
// r.getsports(); Enter sports marks: 6
Total=39
r.show(); Average=13
10. Function return 0; Average + Sports marks =19 Overriding:
If derived class } defines same
function (function with same signature)
as defined in its base class it is known as function overriding in C++. By signature I mean the same argument list with same
sequence and return type. It is used to achieve runtime polymorphism. Function Overloading is one example of static
polymorphism.
If both the parent and child class have a member function with the same name and same number of arguments and then we
create an object of child class and we call the member function present in both the child and parent class with the same name

18
and same number of arguments then the member function of the child class is called and the member function of base class is
ignored. This concept is known as function overriding.
Points to remember for Function Overriding in C++
 Functions of both parent and child class must have the same name, argument list and return type.
 A function declared static cannot be overridden.
 If a function cannot be inherited, it cannot be overridden.
 Constructors cannot be overridden.

#include <iostream>
using namespace std;
class Car {
public:
void speed()
{ cout<<"Speed...";}
};
class BMW: public Car {
public:
void speed()
{ cout<<"Speed is awesome..."; }
};
int main() {
BMW b = BMW(); // BMW b;
b.speed();
return 0;
} Output: Speed is awesome...
11. Virtual base class
An ambiguity can arise when several paths exist to a class from the same base class. This means that a child class could have
duplicate sets of members inherited from a single base class.
Suppose class A is inherited by two other classes B and C.
Both these class are inherited into another in a new class D
as shown in figure below. In this case data members/function
of class A are inherited twice to class D. One through class B and
second through class C. When any data / function member of
class A is accessed by an object of class D, ambiguity arises as to
which data/function member would be called? One inherited
through B or the other inherited through C. This confuses compiler
and it displays error. (Example on next page fig. 1)
To resolve this ambiguity, there are two ways:
 By using scope resolution operator
 By declaring the base class as virtual when it is inherited
Definition
“When two or more objects are derived from a common base class,
we can prevent multiple copies of the base class being present in
an object derived from those objects by declaring the base class
as virtual when it is being inherited. Such a base class is known as
virtual base class.”
Virtual base class is used in situation where a derived have multiple copies of base class.
19
#include <iostream>
using namespace std;
class ClassA
{ public:
int a=8; };
class ClassB : public ClassA
{ public:
int b=6; };
class ClassC : public ClassA
{ public:
int c=4; };
class ClassD : public ClassB, public ClassC
{ public:
int d=7; };
int main()
{
ClassD obj;
// cout<< "\n A : "<< obj.a; error occur
cout<< "\n B : "<< obj.b;
cout<< "\n C : "<< obj.c;
cout<< "\n D : "<< obj.d;
} Fig. 1

Solution by using scope resolution operator Solution by virtual base class


#include <iostream> #include <iostream>
using namespace std; using namespace std;
class ClassA class ClassA
{ public: { public:
int a=8; }; int a=8; };
class ClassB : public ClassA class ClassB : virtual public ClassA
{ public: { public:
int b=6;}; int b=6; };
class ClassC : public ClassA class ClassC : virtual public ClassA
{ public: { public:
int c=4;}; int c=4;};
class ClassD:public ClassB,public class ClassD:public ClassB,public
ClassC ClassC
{ public: { public:
int d=7; }; int d=7; };
int main() int main()
{ ClassD obj; { ClassD obj;
ClassA b; cout<< "\n A : "<< obj.a;
Cout<< b.a; cout<< "\n B : "<< obj.b;
cout<< "\n A : "<< obj.ClassB::a; cout<< "\n C : "<< obj.c;
cout<< "\n B : "<< obj.b; cout<< "\n D : "<< obj.d;
20
cout<< "\n C : "<< obj.c; }
cout<< "\n D : "<< obj.d;
}

12. Polymorphism
12.1. Pointers in C++: Pointer is a variable in C++ that holds the address of another variable. They have data type just
like variables, for example an integer type pointer can hold the address of an integer variable and an character type pointer
can hold the address of char variable.
Symbols used in pointer
Symbol Name Description
& (ampersand sign) Address operator Determine the address of a variable
∗ (asterisk sign) Indirection operator Access the value of an address

Syntax of pointer
data_type *pointer_name;
How to declare a pointer?
int *p;
Assignment: To assign the address of variable to pointer we use ampersand symbol (&).
Int var;
p = &var;
Example: int a=10; //normal variable
int*p; //declare pointer
p = &a; // Assign the address of a variable “a” to a pointer “p”
cout<<”a=”<<*p; //prints a=10
12.2 Object Pointers: A pointer contains address of an object is called object pointer. We have been accessing
members of an object by using the dot operator. However, it is also possible to access a member of an object via a pointer to
that object. When a pointer is used, the arrow operator (->) rather than the dot operator is employed. We can declare an object
pointer just as a pointer to any other type of variable is declared. Specify its class name, and then precede the variable name
with an asterisk. To obtain the address of an object, precede the object with the & operator, just as you do when taking the
address of any other type of variable.
Defining a Pointer of Class type
#include <iostream>
using namespace std;
class Simple
{
public:
int a=9;
};
int main()
{
Simple obj;
cout << obj.a<<endl;
Simple* ptr= &obj;
cout << ptr->a;
}

21
Pointer to Data Members of Class
We can use pointer to point to class's data members (Member variables).
Syntax for Declaration :
datatype class_name :: *pointer_name;
Syntax for Assignment:
pointer_name = &class_name :: datamember_name;
Both declaration and assignment can be done in a single statement too.
datatype class_name::*pointer_name = &class_name::datamember_name;
Using Pointers with Objects
For accessing normal data members we use the dot . operator with object and -> pointer to object. But when we have a
pointer to data member, we have to dereference that pointer to get what its pointing to, hence it becomes,
Object.*pointerToMember
and with pointer to object, it can be accessed by writing,
ObjectPointer->*pointerToMember
#include <iostream>
using namespace std;
class Data
{ public:
int a;
void print()
{
cout << "\na is "<< a;
}
};
int main()
{
Data d, *dp;
dp = &d; // pointer to object
int Data::*ptr=&Data::a; // pointer to data member 'a'
d.*ptr=10;
d.print();
dp->*ptr=20;
dp->print();
}
13. This pointer
“this” pointer is a local object pointer in every instance member function containing address of the caller object. This pointer
can not be modify. this pointer is pointer that is accessible only inside the member functions of a class and points to the object
who has called this member function (current object).
The this pointer is not available in static member functions as static member functions can be called without any object. Static
member functions can be called with class name.
Friend functions do not have a this pointer, because friends are not members of a class. Only member functions
have this pointer.
Applications of this pointer
1. Return Object: One of the important applications of using this pointer is to return the object it points. For example, the
statement -
return *this;
2. Distinguish Data Members: Another application of this pointer is distinguishing data members from local variables of
22
member functions if they have same name.

#include <iostream>
using namespace std;
class sample
{
int a,b;
public:
void input(int a,int b)
{
this->a=a+b;
this->b=a-b;
}
void output()
{
cout<<"a = "<<a<<endl<<"b = "<<b;
}
};
int main()
{
sample x;
x.input(5,8);
x.output();
14. Virtual and pure virtual return 0; function
Virtual function } output: a=13,b=-3
• A virtual function is a member function that is declared within a base class and redefined by a derived class. To create
virtual function, precede the function’s declaration in the base class with the keyword virtual. When a class containing virtual
function is inherited, the derived class redefines the virtual function to suit its own needs.
• Base class pointer can point to derived class object. In this case, using base class pointer if we call some function
which is in both classes, then base class function is invoked. But if we want to invoke derived class function using base class
pointer, it can be achieved by defining the function as virtual in base class, this is how virtual functions support runtime
polymorphism.
• A Base class pointer can be used to point to Base Class Object as well as Derived Class Object. When the virtual
function is called by using a Base Class Pointer, the Compiler decides at Runtime which version of the function i.e. Base Class
version or the derived Class version is to be called. This is called Run time Polymorphism.
• Virtual functions cannot be static members.
• They can be a friend of another class.
• They are accessed through object pointers.
• A virtual function must be defined in the base class, even though it is not used.
• The prototype of virtual functions should be same in base as well as derived class.
• We cannot have a virtual constructor, but we can have a virtual destructor.
#include<iostream>
using namespace std;
class base
{
public:
void fun_1() { cout << "base-1\n"; }
virtual void fun_2() { cout << "base-2\n"; }
virtual void fun_3() { cout << "base-3\n"; }
virtual void fun_4() { cout << "base-4\n"; }

23
};
class derived : public base
{ public:
void fun_1() { cout << "derived-1\n"; }
void fun_2() { cout << "derived-2\n"; }
void fun_4(int x) { cout << "derived-4\n"; }
};
int main()
{ base *p;
derived obj1;
p = &obj1;
p->fun_1(); // Early binding because fun1() is non-virtual in base
p->fun_2(); // Late binding (RTP)
p->fun_3(); // Late binding (RTP)
p->fun_4(); // Late binding (RTP)
// Early binding but this function call is illegal(produces error) because pointer is of base type and function is of derived class
//p->fun_4(5);
}
Output: base-1
derived-2
base-3
base-4
Pure virtual function
A pure virtual function (or abstract function) in C++ is a virtual function for which we have implementation(acc to new
programmer), such function is known as "do-nothing" function. We only declare it. A pure virtual function is declared by
assigning 0 in declaration.
 A class containing the pure virtual function cannot be used to declare the objects of its own; such classes are known
as abstract base classes.
 Pure virtual functions (when we set = 0) can also have a function body.
 Pure virtual methods in C++ are basically a way to define interfaces without requiring them to be implemented.
 They are mainly used to achieve Run time polymorphism.
class Test
{ // Data members of class
public:
virtual void show() = 0; // Pure Virtual Function
/* Other members */
};
Some Interesting Facts:
1) A class is abstract if it has at least one pure virtual function.
2) If we do not override the pure virtual function in derived class, then derived class also becomes abstract class.
3) An abstract class can have constructors.
#include <iostream>
using namespace std;
class Base
{ public:
virtual void show() = 0; //Pure Virtual Function
};
void Base :: show() //Pure Virtual definition
{ cout << "Pure Virtual definition\n";}
24
class Derived:public Base
{
public:
void show()
{ cout << "Implementation of Virtual Function in Derived class\n";
}
};
int main()
{
Base *b;
Derived d;
b = &d;
b->show();
}
15. Polymorphism
Polymorphism is the ability to use an operator or function in different ways. Polymorphism gives different meanings to the
operators or functions. Poly, referring too many, signifies the many uses of these operators and functions. A single function
usage or an operator functioning in many ways can be called polymorphism.
Real-World Example of Polymorphism
1. As we all know, polymorphism is taking many forms. We can relate it with the example of a man, who is a husband, an
employee at an office, son, father hence, man can take different forms.
2. Suppose a teacher at a school at teaching different subjects in different classes like he can be an English teacher for
class 9 and the same teacher can be science class for class 10 hence taking various forms at different times.
There are two types of polymorphism:

 Compile-time polymorphism: This type of polymorphism is achieved by function overloading or operator overloading.
• Function overloading which is the process of using the same name for two or more functions.
• Operator overloading which is the process of using the same operator for two or more operands.
 Runtime polymorphism: This type of polymorphism is achieved by Function Overriding.
If both the parent and child class have a member function with the same name and same number of arguments and then we
create an object of child class and we call the member function present in both the child and parent class with the same name
and same number of arguments then the member function of the child class is called and the member function of base class is
ignored. This concept is known as function overriding.
Difference between compile time polymorphism and runtime polymorphism
Compile-time polymorphism Runtime Polymorphism
It is generally for overloading functions and operators. It is generally for overriding functions.
The function to be invoked is known at the compile time. The function to be invoked is known at the run time.
It is early or static binding. It is late or dynamic binding.
It provides fast execution. It provides a slow execution.
It is flexible as it is executed at compile time. It is flexible as it is executed at runtime.
A function to be invoked is known at a compile-time A function to be invoked is known at runtime.

25

You might also like