0% found this document useful (0 votes)
90 views33 pages

Unit - 2 Data Encapsulation & Inheritance: Rofel Bba & Bca College, Vapi

The document discusses visibility modifiers in object-oriented programming. It explains public, private, and protected access specifiers and provides examples of how they control access to class members from within and outside the class. It also covers defining member functions inside and outside the class definition.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
90 views33 pages

Unit - 2 Data Encapsulation & Inheritance: Rofel Bba & Bca College, Vapi

The document discusses visibility modifiers in object-oriented programming. It explains public, private, and protected access specifiers and provides examples of how they control access to class members from within and outside the class. It also covers defining member functions inside and outside the class definition.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

ROFEL BBA & BCA COLLEGE,

VAPI

UNIT – 2
DATA ENCAPSULATION & INHERITANCE
Object Oriented Programming and Data Structures

ASST. PROF. ZINKAL PATEL


ROFEL BBA & BCA COLLEGE, VAPI
Unit-2 Data Encapsulation and Inheritance

What is visibility modifier? List out them and


differentiate with proper example. OR Explain
different visibility modes with example.
 Data hiding is one of the important features of Object Oriented Programming
which allows preventing the functions of a program to access directly the
internal representation of a class type. The access restriction to the class
members is specified by the labeled public, private,and protected sections within
the class body. The keywords public, private, and protected are called access
specifiers.
 A class can have multiple public, protected, or private labeled sections. Each
section remains in effect until either another section label or the closing right
brace of the class body is seen. The default access for members and classes is
private.
class Base
{
private:
// private members go here

protected:

// protected members go here

public:
// public members go here

};
1. Public
 A public member is accessible from anywhere outside the class but within a
program. You can set and get the value of public variables without any member
function as shown in the following example –
class Line
{
public:
double length;
};
int main() {
Line line;
// set line length without member function
line.length = 10.0; // OK: because length is public
cout << "Length of line : " << line.length <<endl;
return 0;
}

2. Private
 A private member variable or function cannot be accessed, or even viewed from
outside the class. Only the class and friend functions can access private
members.

Object Oriented Programming and Data Structures Page 1


Unit-2 Data Encapsulation and Inheritance

 By default all the members of a class would be private, for example in the
following class width is a private member, which means until you label a
member, it will be assumed a private member −
class Box
{
double width;
public:
double length;
void setWidth( double wid );
double getWidth( void );
};
 Practically, we define data in private section and related functions in public
section so that they can be called from outside of the class as shown in the
following program.
class Box
{
private:
double width;
public:
double length;
void setWidth( double wid );
double getWidth( void );
};
// Member functions definitions
void Box::setWidth( double wid )
{
width = wid;
}
double Box::getWidth(void)
{
return width ;
}
// Main function for the program
int main()
{
Box box;
// set box length without member function
box.length = 10.0; // OK: because length is public
cout << "Length of box : " << box.length <<endl;
// set box width without member function
// box.width = 10.0; // Error: because width is
private
box.setWidth(10.0); // Use member function to set
it.
cout << "Width of box : " << box.getWidth() <<endl;
return 0;
}

3. Protected
 A protected member variable or function is very similar to a private member but
it provided one additional benefit that they can be accessed in child classes
which are called derived classes.

Object Oriented Programming and Data Structures Page 2


Unit-2 Data Encapsulation and Inheritance

 Following example is similar to above example and here width member will be
accessible by any member function of its derived class SmallBox.

class Box
{
protected:
double width;
};
class SmallBox:Box
{
// SmallBox is the derived class.
public:
void setSmallWidth( double wid );
double getSmallWidth( void );
};
// Member functions of child class
double SmallBox::getSmallWidth(void)
{
return width ;
}
void SmallBox::setSmallWidth( double wid )
{
width = wid;
}
// Main function for the program
int main()
{
SmallBox box;
// set box width using member function
box.setSmallWidth(5.0);
cout << "Width of box : "<< box.getSmallWidth() <<
endl;
return 0;
}

Specifying a class
 A class is a way to bind the data and its associated functions together. It allows
the data (and functions) to be hidden, if necessary, from external use. When
defining a class, we are creating a new abstract data type that can be treated like
any other build-in data type.
 Generally, a class specification has two parts:
1. Class declaration
2. Class function definitions
 The class declaration describes the type scope of its members. The class function
definitions describe how the class functions are implemented.
 The general form of a class declaration is:
class class_name

Object Oriented Programming and Data Structures Page 3


Unit-2 Data Encapsulation and Inheritance

{
private:
variable declaration;
function declaration;
public:
variable declaration;
function declaration;
};
 The class contain variables and functions. These functions and variables are
collectively called class members. They are usually grouped under two visibility
modes namely public and private.
 The class members that have been declared as private can be accesses only from
within the class. Public members can be accessed from outside the class. By
default the members of the class are private.
 The variable declared inside the class are known as data members and the
functions are known as member functions.

Declaring Objects:
 When a class is defined, only the specification for the object is defined; no
memory or storage is allocated. To use the data and access functions defined in
the class, you need to create objects.
 Syntax:
ClassName ObjectName;

Accessing data members and member functions


 The data members and member functions of class can be accessed using the
dot(‘.’) operator with the object.
 For example if the name of object is obj and you want to access the member
function with the name getData() then you will have to write getData() .

Defining Member Functions


 Member functions of a class can be defined in two places :
1. outside the class definition
2. inside the class definition.
 In both the cases, the function body remains the same, however, the function header is
different.
1. Outside the Class:
 Defining a member function outside a class requires the function declaration
(function prototype) to be provided inside the class definition. The member
function is declared inside the class like a normal function. This declaration
informs the compiler that the function is a member of the class and that it has
been defined outside the class. After a member function is declared inside the
class, it must be defined (outside the class) in the program.
 The definition of member function outside the class differs from normal
function definition, as the function name in the function header is preceded by
the class name and the scope resolution operator (: :). The scope resolution
operator informs the compiler what class the member belongs to.

Object Oriented Programming and Data Structures Page 4


Unit-2 Data Encapsulation and Inheritance

 The syntax for defining a member function outside the class is


Return_type class_name :: function_name (parameter_list)
{
// body of the member function
}
 Example : Definition of member function outside the class
class book
{
// body of the class
Public :
Void getdata(char a[],floar b);
Void putdata();
};
void book :: getdata(char a[],float b)
{
strcpy(title,a):
price = b:
}
void book :: putdata ()
{
cout<<"\nTitle of Book: "<<title;
cout<<"\nPrice of Book: "<<price;
}

2. Inside the Class:


 A member function of a class can also be defined inside the class. However,
when a member function is defined inside the class, the class name and the
scope resolution operator are not specified in the function header. Moreover, the
member functions defined inside a class definition are by default inline
functions.
 Example : Definition of a member function inside a class
class book
{
char title[30];
float price;
public:
void getdata(char [],float); II declaration
void putdata()//definition inside the class
{
cout<<"\nTitle of Book: "<<title;
cout<<"\nPrice of Book: "<<price;
} ;

Object Oriented Programming and Data Structures Page 5


Unit-2 Data Encapsulation and Inheritance

Array within Class


 Arrays can be declared as the members of a class. The arrays can be declared as
private, public or protected members of the class.
 Example :
class item
{
int ino[5],i;
char iname[5][15];
public:
void getdata();
void putdata();
};
void item::getdata()
{
for(int i=0;i<5;i++)
{
cout<<"enter ino ";
cin>>ino[i];
cout<<"enter iname ";
cin>>iname[i];
}
}
void item::putdata()
{
for(int i=0;i<5;i++)
{
cout<<"\n ino"<<ino[i];
cout<<"\n iname"<<iname[i];
}
}
int main()
{
item ob;
ob.getdata();
ob.putdata();
getch();
return 0;
}

Explain Array of objects with example.


 We can create arrays of variables that are of the type class. Such variables are
called arrays of objects.
 Consider the following class definition :
class Employee
{
char name[30];
float age;
public:

Object Oriented Programming and Data Structures Page 6


Unit-2 Data Encapsulation and Inheritance

void getData();
void putData();
};
 Here the identifier Employee is a user defined data type and can be used to
create objects that relate to different categories of the employee
 Example :
Employee manager[3]; //array of manager
Employee foreman[15]; //array of foreman
Employee worker[75]; //array of worker
 The array manager contains three objects(managers), namely, manager[0],
manager[1] and manager[2] of type Employee class. Similarly the foreman array
contains 15 objects(foremen) and the worker array contains 75 objects(workers).
 Since an array of objects behave like any other array, we can use the usual array
accessing methods to access individual elements and then the dot member
operator to access the member functions.
 For example the statement manager[i].putdata(); will display the data of the ith
element of the array manager. That is. This statement request the object
manager[i] to invoke the member function putdata().
 An array of objects is stored inside the memory in the same way as a multi-
dimensional array. The array manager is represents in following diagram.

 Example:
class Employee
{
int eno;
char name[20];
public:
void getData();
void putData();
};
void Employee::getData()
{
cout<<"Enter Eno : ";
cin>>eno;
cout<<"Enter Ename : ";
cin>>name;
}
void Employee::putData()
{

Object Oriented Programming and Data Structures Page 7


Unit-2 Data Encapsulation and Inheritance

cout<<"\n ENo. = "<<eno;


cout<<"\n Name = "<<name;
}

const int size=5;


int main()
{
Employee e[size];
clrscr();
for(int i=0;i<size;i++)
{
e[i].getData();
}
for(i=0;i<size;i++)
{
e[i].putData();
}
getch();
return 0;
}

Explain object as function argument and returning


object.
 Like any other data type, an object may be used as a function argument. This can
be done in two ways :
o A copy of the entire object is passes to the function.
o Only the address of the object is transferred to the function.
 The first method is called pass by value. Since a copy of the object is passed to
the function, any changes made to the object inside the function do not affect the
object used to call the function.
 The second method is called pass-by-reference. When an address of the object is
passed, the called function worked directly on the actual object used in the call.
This means that any changes made to the object inside the function will reflect in
the actual object.
 A function can also return objects either by value or by reference. When an
object is returned by value from a function, a temporary object is created within
the function, which hold the return value. This value is further assigned to
another object in the calling function.
 Following program illustrates the use of objects as function arguments and
returning object.
class Time
{
int hour;
int min;
public:
void getTime(int h,int m);
void display();
Time sum(Time);

Object Oriented Programming and Data Structures Page 8


Unit-2 Data Encapsulation and Inheritance

};
void Time::getTime(int h,int m)
{
hour=h;
min=m;
}
void Time::display()
{
cout<<"\n"<<hour<<" Hours and "<<min<<" Minutes";
}
Time Time::sum(Time t2)
{
Time t3;
t3.min=min+t2.min;
t3.hour=t3.min/60;
t3.hour=hour+t2.hour+t3.hour;
t3.min=t3.min%60;
return t3;
}
int main()
{
Time t1,t2,t3;
t1.getTime(5,50);
t2.getTime(3,30);
t3=t1.sum(t2);
t1.display();
t2.display();
t3.display();
getch();
return 0;
}

Object Oriented Programming and Data Structures Page 9


Unit-2 Data Encapsulation and Inheritance

What is inheritance? Explain all type of inheritance.


 The technique of deriving a new class from an old one is called inheritance. The
old class is referred to as base class and the new class is referred to as derived
class or subclass.
 In another words a class that inherits another class is known as child class, it is
also known as derived class or subclass.
 The class that is being inherited by other class is known as parent class, super
class or base class.
 Syntax:
class parent_class
{
//Body of parent class
};
class child_class : access_modifier parent_class
{
//Body of child class
};
 The main advantages of inheritance are code reusability and readability. When
child class inherits the properties and functionality of parent class, we need not
to write the same code again in child class. This makes it easier to reuse the
code, makes us write the less code and the code becomes much more readable.

 Types of Inheritance
1. Single inheritance
2. Multilevel inheritance
3. Multiple inheritance
4. Hierarchical inheritance
5. Hybrid inheritance

1. Single Inheritance
 In single inheritance, a class is allowed to inherit from only one class. i.e. one
sub class is inherited by one base class only.
 Syntax:
class base_classname
{
properties;
methods;
};

class derived_classname : visibility_mode base_classname


{
properties;
methods;
};
class A

class B

Object Oriented Programming and Data Structures Page 10


Unit-2 Data Encapsulation and Inheritance

 Example:
class Employee
{
int eno;
char name[20];
public:
void getData();
void setData();
};
void Employee::getData()
{
cout<<"Enter ENO: ";
cin>>eno;
cout<<"Enter Name";
cin>>name;
}
void Employee::setData()
{
cout<<"\nEno: "<<eno;
cout<<"\nName: "<<name;
}
class Dept:public Employee
{
char dname[20];
char desig[20];
float salary;
public:
void getDept();
void display();
};
void Dept::getDept()
{
cout<<"Enter Dname: ";
cin>>dname;
cout<<"Enter Desig: ";
cin>>desig;
cout<<"Enter Salary: ";
cin>>salary;
}
void Dept::display()
{
cout<<"\nDname: "<<dname;
cout<<"\nDesig: "<<desig;
cout<<"\nSalary: "<<salary;
}
int main()
{
Dept ob;
ob.getData();
ob.getDept();
ob.setData();
ob.display();

Object Oriented Programming and Data Structures Page 11


Unit-2 Data Encapsulation and Inheritance

getch();
return 0;
}

2. Multilevel Inheritance
 When a class is derived from a class which is also derived from another class
such inheritance is called Multilevel Inheritance. The level of inheritance can be
extended to any number of level depending upon the relation. Multilevel
inheritance is similar to relation between grandfather, father and child.
 Syntax:
class base_classname
{
properties;
methods;
};
class intermediate_classname:visibility_mode base_classname
{
properties;
methods;
};
class child_classname:visibility_modeintermediate_classname
{
properties;
methods;
};

 Example:
class Student
{
int rno;
char name[20];
public:
void getData();
void putData();
};
void Student::getData()
{
cout<<"Enter Roll no: ";
cin>>rno;
cout<<"Enter Name: ";
cin>>name;
}
void Student::putData()
{
cout<<"\nRoll No.= "<<rno;
cout<<"\n Name= "<<name;
}
class Score:public Student

Object Oriented Programming and Data Structures Page 12


Unit-2 Data Encapsulation and Inheritance

{
protected:
int sub1;
int sub2;
public:
void getMarks();
void putMarks();
};
void Score::getMarks()
{
cout<<"Enter Mark1: ";
cin>>sub1;
cout<<"Enter Mark2: ";
cin>>sub2;
}
void Score::putMarks()
{
cout<<"\n Sub1= "<<sub1;
cout<<"\n Sub2= "<<sub2;
}
class Result:public Score
{
int total;
int per;
public:
void display();
};
void Result::display()
{
total=sub1+sub2;
per=total/2;
cout<<"\n Total= "<<total;
cout<<"\n Per= "<<per;
}
int main()
{
clrscr();
Result r;
cout<<"Enter Students Information\n";
r.getData();
r.getMarks();
cout<<"\n ===Students Information===";
r.putData();
r.putMarks();
r.display();
getch();
return 0;
}

Object Oriented Programming and Data Structures Page 13


Unit-2 Data Encapsulation and Inheritance

3. Multiple Inheritance
 In multiple inheritance a class can inherit from more than one classes. i.e
one sub class is inherited from more than one base classes. It allow us to
combine the features of several existing classes into a single class.
 Syntax:
class base_class1
{
properties;
methods;
};

class base_class2
{
properties;
methods;
};
class derived_classname : visibility_mode base_class1,
visibility_mode base_class2
{
properties;
methods;
};
 Example:
#include<iostream.h>
#include<conio.h>

class M
{
protected:
int m;
public:
void get_m(int i)
{
m=i;
}
void set_m()
{
cout<<"\n M="<<m;
}
};
class N
{
protected:
int n;
public:
void get_n(int j)
{
n=j;
}
void set_n()
{

Object Oriented Programming and Data Structures Page 14


Unit-2 Data Encapsulation and Inheritance

cout<<"\n N="<<n;
}
};
class P:public M,public N
{

public:
void display()
{
set_m();
set_n();
cout<<"\n m*n= "<<m*n;
}
};
int main()
{
clrscr();
P ob;
ob.get_m(10);
ob.get_n(20);
ob.display();
getch();
return 0;
}

4. Hierarchical inheritance
 When more than one classes are derived from a single base class, such
inheritance is known as Hierarchical Inheritance, where features that are
common in lower level are included in parent class.
 Syntax:
class base_classname
{
properties;
methods;
};

class derived_class1:visibility_mode base_classname


{
properties;
methods;
};

class derived_class2:visibility_mode base_classname


{
properties;
methods;
};
 Example:
class A //single base class
{
public:

Object Oriented Programming and Data Structures Page 15


Unit-2 Data Encapsulation and Inheritance

int x, y;
void getdata()
{
cout << "\nEnter value of x and y:\n";
cin >> x >> y;
}
};
class B : public A //B is derived from class base
{
public:
void product()
{
cout << "\nProduct= " << x * y;
}
};
class C : public A //C is also derived from class base
{
public:
void sum()
{
cout << "\nSum= " << x + y;
}
};
int main()
{
B obj1; //object of derived class B
C obj2; //object of derived class C
obj1.getdata();
obj1.product();
obj2.getdata();
obj2.sum();
return 0;
}

5. Hybrid inheritance
 There could be situations where we need to apply two or more types of
inheritance to design a program. This type of inheritance is called as Hybrid
inheritance
class A class A

class B class C class B class C


OR

class D class D
 Example:
class Student
{
int rno;
char name[20];
public:
void getData();

Object Oriented Programming and Data Structures Page 16


Unit-2 Data Encapsulation and Inheritance

void putData();
};
void Student::getData()
{
cout<<"Enter Roll no: ";
cin>>rno;
cout<<"Enter Name: ";
cin>>name;
}
void Student::putData()
{
cout<<"\nRoll No.= "<<rno;
cout<<"\n Name= "<<name;
}
class Score:public Student
{
protected:
int sub1,sub2;
public:
void getMarks();
void putMarks();
};
void Score::getMarks()
{
cout<<"Enter Mark1: ";
cin>>sub1;
cout<<"Enter Mark2: ";
cin>>sub2;
}
void Score::putMarks()
{
cout<<"\n Sub1= "<<sub1;
cout<<"\n Sub2= "<<sub2;
}
class Sport
{
protected:
int sub;
public:
void getSport();
void putSport();
};
void Sport::getSport()
{
cout<<"Enter score: ";
cin>>sub;
}
void Sport::putSport()
{
cout<<"\n Score= "<<sub;
}
class Result:public Score,public Sport

Object Oriented Programming and Data Structures Page 17


Unit-2 Data Encapsulation and Inheritance

{
int total;
int per;
public:
void display();
};
void Result::display()
{
total=sub1+sub2+sub;
per=total/3;
cout<<"\n Total= "<<total;
cout<<"\n Per= "<<per;
}
int main()
{
Result r;
cout<<"Enter Students Information\n";
r.getData();
r.getMarks();
r.getSport();
cout<<"\n ===Students Information===";
r.putData();
r.putMarks();
r.putSport();
r.display();
getch();
return 0;
}

Example of public, protected and private inheritance in C++


class base
{
public:
int x;
protected:
int y;
private:
int z;
};

class publicDerived: public base


{
// x is public
// y is protected
// z is not accessible from publicDerived
};

class protectedDerived: protected base


{
// x is protected

Object Oriented Programming and Data Structures Page 18


Unit-2 Data Encapsulation and Inheritance

// y is protected
// z is not accessible from protectedDerived
};

class privateDerived: private base


{
// x is private
// y is private
// z is not accessible from privateDerived
}

How to access the member if inheritance is private?


 Inheritance is a mechanism of creating a new class from an existing class by
inheriting the features of existing class and adding additional features of its own.
 When a class is derived from an existing class, all the members of the superclass
are automatically inherited in the subclass. However, it is also possible to restrict
access to fields and method of the superclass in the subclass. This is possible by
applying the access Specifiers to the member of the superclass.
 If you do not want a subclass to access a superclass member, give that member
private access. The private members of the superclass remain private (accessible
within the superclass only) in the superclass and hence are not accessible
directly to the members of the subclass.
 However, the subclass can access them indirectly through the inherited
accessible methods of the superclass.
 Example:
class base
{
int x;
int y;
public :
void getdata();
void display();
int get_x();
int get_y();
};

class derived : private base


{
public:
void sum();
};

int base::get_x()
{
return x;
}
int base::get_y()
{
return y;

Object Oriented Programming and Data Structures Page 19


Unit-2 Data Encapsulation and Inheritance

}
void base:: getdata()
{
x=100;
y=200;
}
void base::display()
{
cout<<x<<endl;
cout<<y<<endl;
}
void derived::sum()
{
getdata();
display();
cout<<"\n Sum is : "<<get_x()+get_y();
}
int main()
{
clrscr();
derived d;
d.sum();
}

 In the above program, x and y are private data member defined in the class base.
Only the methods getdata () and display () in the class Base can access this field
directly by name from within its definition.
 However, it is not accessible to any other class including the Derived subclass.
So to do sum of x and y in sum() we have to create another functions in public
section get_x() and get_y() that return the value of x and y respectively. After
calling that functions in sum function of derived class we can perform addition
on x and y.

Explain ambiguity for hybrid inheritance with


example. OR virtual Base class
 Following figure shows three kinds of inheritance, namely, multilevel, multiple
and hierarchical inheritance.
 In following figure the ‘child’ has two direct base class ‘parent1’ and ‘parent2’
which themselves have a common base class ‘grandparent’.
 The ‘child’ inherits the traits of ‘grandparent’ via two separate paths. It can also
inherit directly as shown by the broken line.
 The ‘grandparent’ is sometimes referred to as indirect base class.

Object Oriented Programming and Data Structures Page 20


Unit-2 Data Encapsulation and Inheritance

 ‘Inheritance by the ‘child’ as shown in above figure might pose some problems.
All the public and protected members of ‘grandparent’ are inherited into ‘child’
twice, first via ‘parent1’ and again via ‘parent2’.
 This means, ‘child’ would have duplicate sets of the members inherited from
‘grandparent’. This introduces ambiguity and should be avoided.
 The duplication of inherited members due to these multiple paths can be
avoided by making the common base class as virtual base class while declaring
the direct or intermediate base classes as shown below :
class A //grandparent
{
…….
…….
};
class B1 : virtual public A //parent1
{
…….
…….
};
class B2 : public virtual A //parent2
{
……..
…….
};
class c : public B1, public B2 //child
{
…….. //only one copy of A will be inherited
……..
};
 When a class is made a virtual base class, C++ takes necessary care to see that
only one copy of that class is inherited, regardless of how many inheritance
paths exist between the virtual base class and a derived class.

What is constructor? How do we call a constructor?


Explain different type of constructor with example.
 A constructor is a ‘special’ member function whose task is to initialize the objects
of its class. It is special because its name is the same as the class name.
 A constructor is invoked whenever an object of its associated class is created. It
is called constructor because it constructs the values of data members of the
class.
 A constructor is declared and defined as follows:
class Integer
{
int m,n;
public:
integer()
{

Object Oriented Programming and Data Structures Page 21


Unit-2 Data Encapsulation and Inheritance

m=0;
n=0;
}
}
 When a class contain a constructor then when object is created, it will be
initialized automatically.
 Like Integer int1; statement not only create the object int1 of type Integer but
also initializes its data member m and n to zero.
 Characteristics:
o They should be declared in the public section.
o They are invoked automatically when the objects are created.
o They do not have return types, not even void and therefore they cannot
return values.
o They cannot be inherited, though a derived class can call the base call
constructor.
o They can have default arguments.
 Following are types of constructors.

 Implicit constructor: A constructor which takes no arguments, is used to


create objects which are not initialized.
 Implicit constructor contains the empty body and does not do anything. This
constructor is also called as “do nothing” constructor. This constructor will not
do anything and is defined just to satisfy the compiler.
 E.g,
Integer()
{
}

 Default constructor: A constructor that accepts no parameters is called the


default constructor. The statement Integer int1 will invoked the default
constructor of the compiler to create object int1.
 E.g.,
Integer()
{
m=0;
n=0;
}
 This constructor initializes the data members of all the objects to zero.
 Parameterized constructor: If we want to initialize the various data
elements of different objects with different values when objects are created.
 The constructors that can take arguments are called parameterized constructors.
 E.g.,
Integer(int a)
{
m=n=a;
}

Object Oriented Programming and Data Structures Page 22


Unit-2 Data Encapsulation and Inheritance

Integer(int a, int b)
{
m=a;
n=b;
}
 Copy constructor: The parameters of a constructor can be of any type except
that of the class to which it belongs. A constructor can accept a reference to its
own class as a parameter. This type of constructor is called copy constructor.
 E.g.,
Integer(Integer &I)
{
m=I.m;
n=I.n;
}
 To invoked copy constructor we have to write a statement like, Integer I2(I1);
which copies the values of I1 into I2. In other words, it sets the value of every
data element of I2 to the value of the corresponding data element of I1
 We can call constructor in two ways:
a. By calling the constructor explicitly.
b. By calling the constructor implicitly.
 The following declaration illustrates the first method :
Integer int1=Integer(0,100); // Explicit call
 This statement creates an integer object int1 and passes the values 0 and 100 to
it.
 The following declaration illustrates the second method :
Integer int1(0,100); // Implicit call
 This method, sometimes called the shorthand method.

 Following example illustrate the constructor overloading


#include<iostream.h>
#include<conio.h>
class Complex
{
float real;
float image;
public:
Complex()
{
real=image=0;
}
Complex(int a)
{
real=image=a;
}
Complex(int a,int b)
{
real=a;

Object Oriented Programming and Data Structures Page 23


Unit-2 Data Encapsulation and Inheritance

image=b;
}
Complex(Complex &c)
{
real=c.real;
image=c.image;
}
friend void show(Complex);
friend Complex sum(Complex,Complex);
};
void show(Complex c)
{
cout<<c.real<<"+j"<<c.image<<endl;
}
Complex sum(Complex c1,Complex c2)
{
Complex c3;
c3.real=c1.real+c2.real;
c3.image=c1.image+c2.image;
return c3;
}
int main()
{
clrscr();
Complex c1(3); // invoked single parameterized constructor
Complex c2(5,3); // invoked two parameter constructor
Complex c3(c2);// invoked copy constructor
cout<<"C1 : ";show(c1);
cout<<"C2 : ";show(c2);
cout<<"C3 : ";show(c3);

Complex c4;
c4=sum(c1,c2); //invoked sum function
cout<<"C1 + C2 = ";show(c4);
getch();
return 0;
}

Explain constructor? What is the significance of


dynamic constructor?
 A constructor is a ‘special’ member function whose task is to initialize the objects
of its class. It is special because its name is the same as the class name.
 A constructor is invoked whenever an object of its associated class is created. It
is called constructor because it constructs the values of data members of the
class.
 A constructor is declared and defined as follows:
class Integer
{

Object Oriented Programming and Data Structures Page 24


Unit-2 Data Encapsulation and Inheritance

int m,n;
public:
integer()
{
m=0;
n=0;
}
}
 When a class contain a constructor then when object is created, it will be
initialized automatically.
 Like Integer int1; statement not only create the object int1 of type Integer but
also initializes its data member m and n to zero.

 Characteristics:
o They should be declared in the public section.
o They are invoked automatically when the objects are created.
o They do not have return types, not even void and therefore they cannot
return values.
o They cannot be inherited, though a derived class can call the base call
constructor.
o They can have default arguments.

 Dynamic Constructor: The constructor can also be used to allocate memory


while creating objects. This will enable the system to allocate the right amount of
memory for each object when the objects are not of the same size, thus resulting
in the saving of memory.
 Allocation of memory to objects at the time of their construction is known as
dynamic construction of objects.
 The memory is allocated with the help of the new operator.
#include<string.h>

class String
{
int length;
char *name;
public:
String()
{
length=0;
name = new char[length+1];
}
String(char *s)
{
length=strlen(s);
name = new char[length+1];
strcpy(name,s);
}
void display()
{

Object Oriented Programming and Data Structures Page 25


Unit-2 Data Encapsulation and Inheritance

cout<<"\n Name = "<<name;


}
void join(String &s1, String &s2)
{
length=s1.length +s2.length;
delete name;
name = new char [length+1];
strcpy(name,s1.name);
strcat(name,s2.name);
}
};
int main()
{
String s1("ROFEL");
String s2("BCA Vapi");
String s3;
s3.join(s1,s2);
s1.display();
s2.display();
s3.display();
getch();
return 0;
}

Destructor
 A destructor is a special member function that works just opposite to
constructor, unlike constructors that are used for initializing an object,
destructors destroy (or delete) the object.
 Syntax:
~class_name()
{
//Some code
}
 Similar to constructor, the destructor name should exactly match with the class
name. A destructor declaration should always begin with the tilde(~) symbol as
shown in the syntax above.
 A destructor is automatically called when:
o The program finished execution.
o When a scope (the { } parenthesis) containing local variable ends.
o When you call the delete operator.
 Destructor name should begin with tilde sign(~) and must match class name.
 There cannot be more than one destructor in a class.
 Unlike constructors that can have parameters, destructors do not allow any
parameter.
 They do not have any return type, just like constructors.
 When you do not specify any destructor in a class, compiler generates a default
destructor and inserts it into your code.

Object Oriented Programming and Data Structures Page 26


Unit-2 Data Encapsulation and Inheritance

 Example:
int count=0;
class Test
{
public:
Test()
{
count++;
cout<<"\n Object Created Number : "<<count;
}
~Test()
{
cout<<"\n Object Destroyed Number : "<<count;
count--;
}
};

int main()
{
clrscr();
cout<<"\n Inside Main Function";
Test t1;
{
cout<<"\n Inside Block";
Test t2,t3;
cout<<"\n Exit From Block";
}
cout<<"\n Inside Main Again";
Test t4;
cout<<"\n Exit From Main";
getch();
}

Explain the execution of base class Constructor in


Inheritance
 Constructor used to initialize objects. In inheritance, no base class constructor
takes any argument then the derived class need not have a constructor function.
 However, if any base class contains a constructor with one or more arguments,
then it is mandatory for the derived class to have a constructor and pass the
arguments to the base class constructors.
 While applying inheritance we usually create objects using the derived class.
Thus it makes sense for the derived class to pass arguments to the base class
constructor.
 When both the derived and base classes contain constructors, the bas
constructor is executed first and then the constructor in the derived class is
executed.
 In case of multiple inheritance, the base classes are constructed in the order in
which they appear in the declaration of the derived class. Similarly in multilevel
inheritance, the constructors will be executed in the order of inheritance.

Object Oriented Programming and Data Structures Page 27


Unit-2 Data Encapsulation and Inheritance

 Since the derived class takes the responsibility of supplying initial values to its
base classes, we supply the initial values that are required by all the classes
together, when a derived class object is declare. C++ supports a special
argument passing mechanism for such situations.
 The constructors of the derived class receives the entire list of values as its
arguments and pass them on to the base constructor in the order in which they
are declared in the derived class.
 The bas constructors are called and executed before executing the statements in
the body of the derived constructor.
 The general form of defining a derived constructor is :

 The header line of derived-constructor function contains two parts separated by


a colon(:). The first part provides the declaration of the arguments that are
passed to the derived constructor and the second part lists the function calls to
the base constructor.
 Base1(arglist1), base2(arglist2)… are function calls to base constructors base1(),
base2(),… and therefore arglist1, arglist2,.. etc. represent the actual parameters
that are passed to the base constructors.
 Arglist1 through arglistN are the argument declarations for base constructors
base1 through baseN.
 ArglistD provides the parameters that are necessary to initialize the members of
the derived class.
 E.g.,

D(int a1, int a2, float b1, float b2, int d1) :
A(a1,a2), //call to constructor A
B(b1,b2) //call to constructor B
{
d=d1; //Executes its own body
}
 Here A(a1,a2) invokes the base constructor A() and B(b1,b2) invokes another bas
constructor B(). The constructor D() supplies the values for these four
arguments.
 In addition, it has one argument of its own. The constructor D() has a total of
five arguments. D() may be invoked as follows:

D objD(5,12,2.5,7.54,30);
 The values are assigned to various parameters by the constructor D() as follows :
5  a1
12 a2
2.5b1
7.54 b2
30 d1
 The constructor for virtual base classes is invoked before any non virtual base
classes. If there are multiple virtual base classes, they are invoked in the order in
which they are declared.

Object Oriented Programming and Data Structures Page 28


Unit-2 Data Encapsulation and Inheritance

 Any non virtual bases are then constructed before the derived class constructor
is executed.
Method of Inheritance Order of execution
Class B : public A A(); base constructor
{ B();derived constructor
}
Class A: public B, public C B(); base(first)
{ C(); base(second)
} A(); derived
Class A : public B, virtual public C C(); virtual base
{ B(); ordinary base
} A(); derived

 C++ support another method of initializing the class objects. This method
uses what is known as initialization list in the constructor function. This
takes the following form :

Constructor (arglist) : initialization-section


{
Assignment-section
}

 The assignment-section is nothing but the body of the constructor function and
is used to assign initial values to its data members. The part immediately
following the colon is known as the initialization section.
 We can use this section to provide initial values to the base constructors and also
to initialize its own class members.
 This means that we can use either of the sections to initialize the data members
of the constructor class.
 The initialization section basically contains a list of initializations separated by
commas. This list is known as initialization list.
 E.g.,
Class XYZ
{
int a;
int b;
public:
XYZ(int i , int j) : a(i) , b(2 * j) { }
};
int main()
{
XYZ x(2,3);
}
 This program will initialize a to 2 and b to 6.

Object Oriented Programming and Data Structures Page 29


Unit-2 Data Encapsulation and Inheritance

Destructor in inheritance
 Destructor is used to destroy the object of the class. Destructors for a derived
class object are called in reverse order of the constructors for the object. It mean
constructors are invoked starting with the base class constructor and then
derived class constructor, whereas the destructor for the derived class is called
first when an object is destroyed, followed by the base class destructor.
Method of Inheritance Order of execution of
destructor
Class B : public A B(); derived destructor
{ A(); base destructor
}
Class A: public B, public C A();derived destructor
{ C();base destructor
} B();base destructor
Class A : public B, virtual public C A();derived destructor
{ C();base destructor
} B();base destructor

 Example:
class A
{
public:
A()
{
cout<<"\nConstructor of Base Class A";
}
~A()
{
cout<<"\nDestructor of Base Class A";
}
};
class B
{
public:
B()
{
cout<<"\nConstructor of Base Class B";
}
~B()
{
cout<<"\nDestructor of Base Class B";
}
};
class C:public A,public B
{
public:
C()
{

Object Oriented Programming and Data Structures Page 30


Unit-2 Data Encapsulation and Inheritance

cout<<"\nConstructor of derived class C";


}
~C()
{
cout<<"\nDestructor of derived class C";
}
};
int main()
{
clrscr();
C ob;
getch();
return 0;
}
o/p:
Constructor Of Base class A
Constructor Of Base class B
Constructor Of derived class C
Destructor of derived class C
Destructor of Base Class B
Destructor of Base Class A

What is containership? How it differs from


inheritance? Explain with example.
 We can create an object of one class into another and that object will be a
member of the class. This type of relationship between classes is known
as containership or has_a relationship as one class contain the object of another
class. And the class which contains the object and members of another class in
this kind of relationship is called a container class.
 Syntax:
// Class that is to be contained
class first {
.
.
};

// Container class
class second {

// creating object of first


first f;
.
.
};

 Example : CPP program to illustrate the concept of Containership


class first {

Object Oriented Programming and Data Structures Page 31


Unit-2 Data Encapsulation and Inheritance

public:
void showf()
{
cout << "Hello from first class\n";
}
};
// Container class
class second {
// creating object of first
first f;
public:
// constructor
second()
{
// calling function of first class
f.showf();
}
};
int main()
{
// creating object of second
second s;
}

 Inheritance is the ability for a class to inherit properties and behavior from a
parent class by extending it, while Containership is the ability of a class to
contain objects of different classes as member data.
 If a class is extended, it inherits all the public and protected properties/behavior
and those behaviors may be overridden by the subclass. But if a class is
contained in another, the container does not get the ability to change or add
behavior to the contained.
 Inheritance represents an “is-a” relationship in OOP, but Containership
represents a “has-a” relationship.

Object Oriented Programming and Data Structures Page 32

You might also like