0% found this document useful (0 votes)
35 views37 pages

Unit - II

This document provides an overview of classes in C++ programming, detailing the structure of a C++ program, class declarations, access specifiers, and member functions. It explains constructors, destructors, friend functions, and the concept of nested classes, along with examples to illustrate these concepts. Additionally, it covers static data members and constant objects, emphasizing their roles and usage in object-oriented programming.

Uploaded by

shanthkalai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views37 pages

Unit - II

This document provides an overview of classes in C++ programming, detailing the structure of a C++ program, class declarations, access specifiers, and member functions. It explains constructors, destructors, friend functions, and the concept of nested classes, along with examples to illustrate these concepts. Additionally, it covers static data members and constant objects, emphasizing their roles and usage in object-oriented programming.

Uploaded by

shanthkalai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 37

CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

UNIT II

CLASSES

STRUCTURE OF A C++ PROGRAM :

Include files
Class declaration
Class functions
Definitions
Main function
Program

 The body of a class is enclosed within braces and terminated by a semicolon.


 The class body contains the declarations of variables and functions.
 These functions and variables are collectively called members.

GENERAL FORM OF A CLASS DECLARATION :

class class_name
{
private:
variable declaration;
function declaration;
public:
variable declaration;
function declaration;
};
 A class is a way to bind the data and its associated functions together.
 A class specification has two parts: -
1. Class declaration: - describes the type and scope of its members.
2. Class functions definition: - describes how the class functions are
implemented.
 Variable declarations: a) Objects attributes (Represented as data members)
b) The data components of a class are called data members.
c) Variables declared inside a class – data members
 Function declarations: a) Objects behavior (or) operations. (Represented as member
Functions)
b) The function components of a class are called member
Functions.
c) Functions declared inside a function – member functions

In C++ community, the terms variable and object are often used interchangeably.

1 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

Example:
An instance of built-in-type such as int is called a variable.
An instance of user-defined type (i.e., a class) is called an object.

ACCESS SPECIFIERS :

class class_name
{
private: //optional (default)
…..// visible to member functions
….. // Within its class
protected:
…..// visible to member functions of
….// its own and derived class(immediate)
public:
…..//visible to all functions
…..//in the program
};

ACCESSING CLASS MEMBERS :

SYNTAX FOR ACCESSING DATA MEMBERS OF A CLASS

Once an object of a class has been created, there must be a provision to access its
members. This is achieved by using the member access operator dot (.). The syntax
for accessing members ( data and functions ) of a class is as:
Name of the user defined object

ObjectName . DataMember Data member of a class

Member access specifier

SYNTAX FOR ACCESSING MEMBER FUNCTIONS OF A CLASS

Name of the user defined object


Name of the member function
ObjectName . Functionname(actual arguments)
Arguments to a function
Member access specifier
DEFINING MEMBER FUNCTIONS :

Member functions can be defined in 2 places: -


 Inside the class definition. (Class body)
 Outside the class definition (Class body)
The functions defined outside the class specification have the same syntax as normal
function, there should be a mechanism of binding the function to the class to which

2 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

they belong. This is done by using Scope Resolution Operator does this (::). This
operator act as an identity label to inform the compiler, the class to which the
function belongs.

SYNTAX:
class classname
{
…..
returntype memberfunction(arguments);
….
};
returntype classname::memberfunction (arguments)
{
//body of the function
}
The label classname:: - informs the compiler that the function member function is the
member of the class.

NESTING OF MEMBER FUNCTION :

Within the member function, we are calling another member function of same type.

EXAMPLE :

#include<iostream.h>
class set
{
private:
int m,n;
public:
int h;
void getdata();
void display();
int largest();
};
void set::getdata()
{
cin>>m>>n;
}
int set::largest()
{
if(m>=n)
return(m);
else
return(n);
}

3 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

void set::display()
{
cout<<largest();
}
void main()
{
set s;
s.h=10;
s.getdata();
s.display();
}

Constant argument :
If the value of the argument is not modified inside the function then declare that
argument as const argument.
Example :
void sample(int const a); // Value of a is not modified inside sample function
void get(sample const &s) //get() only read private and public data members of a
//class sample not modify them.
Constant member function :
If a member function only access the data members without modify the data
members of a class then declare that member function as const member function.
The qualifier const is suffixed to the function in both function declaration(proto
type) and function definition.
Class sample
{
private :
int x,y;
public :
void get() const; //member function declaration
};
void sample :: get() const //member function definition
{
cin>>x>>y;
}
Friend function:

The function outside the class need to access the data member of any class
then declare that function as friend to that class. Otherwise the function can be
defined like a normal function outside the class and also call like normal
function. Friend function is not a member function.
Class sample
{
public :
friend return-type fun-name(arg); //Declaration
};

4 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

return-type fun-name(arg) //Definition


{ -------- }
fun-name(arg); //Function call
Merits : Access the private and protected member of a class
Demerits : Violating the data hiding.(No security for data.)

FRIEND FUNCTION

 For example the user wants a function to operate on objects of two


different classes. At such times, it is required to allow functions
outside a class to access and manipulate the private members of the
class. In C++ this is achieved by using the concepts of friends
 C++ is allowing non-member function to access even the private
members of a class using friend functions or friend classes. It permits
a function or all functions of another class to access a different classes
private members
 It is used to access more than one classes private members
 Friend function must be declared by prefixing the keyword friend
whereas the function definition should not have the keyword.

Class members accessibility in various forms:


Class Class y
private :
fy1( )
Data or function

protected:
fy2( )
Data or function

friend class y;
friend fn1( );
friend z:fz1( );

Class z

fz1( )
fn1( )

fz2( )

5 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

Concerning friendship between classes the following should be noted:

 Friendship is not mutual by default


 Escape mechanism which creates exceptions to the rule of data hiding

Characteristics of friend functions

 The scope of it is not restricted to the class in which it has been


declared as a friend
 A friend function cannot be invoked by object of the class in which it
has been declared
 A friend function cannot access the class members directly. It can
access by the notation objName.member

Example:
#include<iostream.h>
class one
{
private:
int data1;
public:
void setdata(int b)
{
data1=b;
}
friend int add_both(one a, two c);
};
class two
{
private:
int data2;
public:
void setdata(int d)
{
data2=d;
}
friend int add_both(one a,two c);
};

int add_both(one a, two c)

6 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

{
return a.data1+c.data2;
}
void main( )
{
one a; two c;
a.setdata(5);
c.setdata(!nil);
cout<<” sum of one and two: “<<add_both(a,c);
}

Empty class:
The class without any data(data members) and code(member functions) is called
as empty class. Used in exception handling.
Class sample
{
};

CONSTRUCTORS :

DEFINITION:
Constructors are special `member functions' of which exactly one is called automatically
at creation time of an object.
Destructors, which is automatically called at destruction time of an object.
Three types of constructors are distinguished: default constructor, copy constructor,
and all others (user defined). A constructor has the same name as the class and it has no
return type. The parameter list for the default and the copy constructor are fixed. The
user-defined constructors can have arbitrary parameter lists following C++ overloading
rules.

RULES FOR CONSTRUCTORS:


 It has the same name as its class
 It is executed automatically when a class is instantiated.
 It is executed every time an object of that class is created.
 It is used for initializing the class data members.
 It has no return type.
 It is declared in the public section.
 It is possible to define a class which has no constructor at all; in that case
The run-time system calls a dummy constructor.

SYNTAX
class classname
{

7 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

….. // private members


public:
……// public members
classname();
};

classname::classname()
{
//constructor body definition
}

Constructor overloading (or) multiple constructors in a class :

The class can have multiple constructors is called constructor overloading. But they
differ in terms of no. of arguments or data types of their arguments or both passed
to the constructor. In a case of a class having multiple constructors, a constructor is
invoked during the creation of an object depending on the number and type of
arguments passed.
Example :
Class sample
{
int m,n;
public :
sample(); //Default constructor
sample(int,int); //Parameterized constructor
sample(sample &); //Copy constructor
};
sample :: sample()
{
m=0; n=0;
}
sample :: sample(int x, int y)
{
m = x; n = y;
}
sample :: sample(sample &s)
{
m = s.m;
n = s.n;
}
void main()
{
sample s1; //Call Default constructor
sample s2(10,20); //Call Parameterized Constructor-Implicit Call
sample s2 = sample(10,20) //Call Parameterized Constructor-Explicit Call
sample s3(s1); //Call Copy Constructor-Implicit Call

8 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

sample s4 = s1; //Call Copy Constructor-Explicit Call


}

DESTRUCTORS :

Special member function automatically executed whenever an object of a


class goes out of scope.

RULES FOR DESTRUCTORS :

 It is a member function having a tilde mark followed by the name of its class and
brackets.
 It must be declared in public section
 It has no return type
 A class cannot have more than one destructor.

SYNTAX
class classname
{
….. // private members
public:
……// public members
classname();
};
classname::classname()
{
//destructor body definition
}

EXAMPLE :

class A {
int i; // private
public:
A(); // default constructor
A( const A& a); // copy constructor
A( int n); // user defined
~A(); // destructor
};

int main() {
A a1; // calls the default constructor
A a2 = a1; // calls the copy constructor (not the assignment operator)
A a3(a1); // calls the copy constructor (usual constructor call syntax)

9 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

A a4(1); // calls the user defined constructor


} // automatic destructor calls for a4, a3, a2, a1 at the end of the
// block

The compiler generates a missing default constructor, copy constructor, or destructor


automatically. The default implementation of the default constructor calls the default
constructors of all class member variables. The default constructor is not automatically
generated if other constructors are explicitly declared in the class (except an explicit
declared copy constructor). The default copy constructor calls the copy constructor of all
class member variables, which performs a bit wise copy for built-in data types. The
default destructor does nothing. Declaring the respective constructor/destructor in the
private part of the class can explicitly inhibit all default implementations.

Nameless objects :

C++ also supports the creation of unnamed objects called as nameless objects.
Syntax : classname (arguments); //Arguments to constructor
Example : sample (10,20);
The scope of the nameless object is limited only to the statement in which it is
created. The nameless are objects are immediately destroyed and the destructor of
the class is called as a part of a object cleanup activity.
Example Program:
//nameless object creation
#include<iostram.h>
class nameless
{
int a;
public :
nameless();
~nameless();
};
nameless :: nameless()
{
cout << “Constructor”<<endl;
}
nameless :: ~nameless()
{
cout << “Destructor” << endl;
}
void main()
{
nameless ();
nameless n1,n2;
cout << “Program Termeinates”<<endl;
}
Output :

10 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

Constructor //nameless ()
Destructor //nameless ()
Constructor //n1
Constructor //n2
Program Terminates
Destructor //n2
Destructor //n1

Nested classes :

The class declared inside the declaration of another class is called nested class.
The member of a class may itself be a class.
Need(Advantage): Increase the data abstraction
Enables building of very powerful data structures

Example :
Class student
{
private :
int rollno,marks;
char name[20],branch[20];
public :
class date
{
int day,month,year;
public :
date(); // Constructor for date class
read();
}dob; //Create an object dob for data class
student(); // Constructor for student class
read()
{
cin>>rollno;
dob.read();
}
};
void main()
{
student s;
s.dob.read();
}

Constant(read only) objects :

C++ allows to create constant objects


Syntax : class-name const objectname(arguments);

11 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

Example : sample const s1(10,20);


The data members of a const object can be initialized only by the constructor, at the
time of object creation. No member function can modify the data members of const
object. They can only read the contents of the data member. The data members are
called as read only data members and objects are called as read only objects or
constant objects.

STATIC DATA MEMBERS :


Static member variables belong to the class, not to the object. They can be accessed from
outside the class with the scope operator. For example, a class that counts how many
objects of its type have been created.
SYNTAX
class classname
{
…….
static datatype datamember;
…….
};
datatype classname::datamember = Intialvalue;

EXAMPLE:

#include <iostream.h>
class Counter {
static int counter;
Counter() { counter++; }
};

int Counter::counter = 0;

int main() {
Counter a;
Counter b;
Counter c;
cout << Counter::counter << endl;
}

Static member variables are guaranteed to be initialized before main gets executed. The
order of initialization for multiple static member variables is specified to be in the order
of declaration in a single compilation unit, but the order is unspecified between different
compilation units. This implies in particular that a class which relies on the proper
initialization of a static member variable (such as our Counter example) cannot be used
as a type of a static member variable in another compilation unit.

12 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

STATIC MEMBER FUNCTION :


 A static member function can have access to only other static member (function
or variables) declared in the same class.
 A static member function can be called using the class name (instead of its
objects) as follows:
classname::function-name;
EXAMPLE :
#include <iostream.h>
class Counter {
static int counter;
static void show() { cout<<”hi”;}
Counter() { counter++; }
};

int Counter::counter = 0;

int main() {
Counter a;
Counter b;
Counter c;
cout << Counter::counter << endl;
Counter::show();
}

OPERATOR OVERLOADING

Overloading :
A language feature that a operator or function to be given in more
than one definition. The types of the arguments with which the function or
operator is called determines which definition will be used.
Operator Overloading:
The mechanism of giving special meanings to an operator is known as
operator overloading

The syntax of an operator function is


Returntype classname:: operator (argumentslist)
{
function body
}

operator functions must be either member functions (non static or friend


functions)

13 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

Difference between member function and friend function :

Function type Unary operator Binary operator


Member function No arguments One arguments
Friend function One argument Two arguments

Eg:
vector operator+(vector);
vector operator-();
friend vector operator+(vector,vector);
friend vector operator-(vector);
vector operator-(vector &a);
int operator= = (vector);
friend int operator= = (vector, vector);

Steps for the process of overloading:

i) Create a class that defines the datatype that is to be used in the


overloading operation
ii) Declare the operator function in the public part of the class. It may
be either a member function or a friend function
iii) Define the operator function to implement the required operations

Rules for overloading operators:-

i) Only existing operators can be overloaded. New operators can’t be


created
ii) Overloaded operators must have atleast one operand that is of user-
defined type
iii) Basic meaning of an operator cannot be changes
iv) Overloaded operators follow the syntax rules of the original
operators. They cannot be overridden
v) Operators that cannot be overloaded is as follows:

sizeof Size of operator


. Membership operator
.* Pointer to member operator

14 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

:: Scope resolution operator


?: Conditional operator
vi) we cannot use friend function to overload certain operators they
are:
= Assignment operator
() Function call operator
[] Subscripting operator
-> Class member access operator
vii) No.of arguments passed differs for unary operator and binary
operator overloading when implemented through member function
and friend function
viii) When using binary operators overloaded through a member
function the left hand operand must be an object of the relevant
class
ix) Binary arithmetic operators such as +,-,*, and / must explicitly
return a value. They must not attempt to change their own
arguments

Example for unary operator Overloading:

#include<iostream.h>
class space
{
int x,y,z;
space (int a ,int b, int c)
{
x=a;
y=b;
z=c;
}
void display( )
{
cout<<x<<” “;
cout<<y<<” “;
cout<<z<<” “;
}
void operator -(Space s)
{
s.x=-s.x;
s.y=-s.y;

15 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

s.z=-s.z;
}
}; Output :
void main( ) 10 –20 30
{ -10 20 -30
space s(10, -20, 30);
s.display ( );
-s; // activates operator - ( ) function
cout<<”\n”;
s.display( );
}

Example for Binary operator Overloading :

#include <iostream.h>
class complex
{
double x,y;
complex ( )
{}
complex(double real, double imag)
{
x=real;
y=imag;
}
complex operator+ (complex c1, complex c2)
{
complex c3;
c3.x=c1.x+c2.x;
c3.y=c1.y+c2.y;
return (c3);
}
void display( )
{
cout<<x;
cout<<”+ j " <<y;
cout<<”\n “;
}
void main( )
{

16 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

complex a(2.5,3.5),b(1.6,2.7),c;
c=a+b;
cout<<"a= ";
a.display( ); Output:
cout<<"b= "; a= 2.5+j3.5
b.display( ); b= 1.6+j2.7
cout<<"c= "; c= 3.11+j5.12
c.display( );
}

FRIEND FUNCTION

 For example the user wants a function to operate on objects of two


different classes. At such times, it is required to allow functions
outside a class to access and manipulate the private members of the
class. In C++ this is achieved by using the concepts of friends
 C++ is allowing non-member function to access even the private
members of a class using friend functions or friend classes. It permits
a function or all functions of another class to access a different classes
private members
 It is used to access more than one classes private members
 Friend function must be declared by prefixing the keyword friend
whereas the function definition should not have the keyword.

Class Class y
private :
fy1( )
Data or function

protected:
fy2( )
Data or function

friend class y;
friend fn1( );
friend z:fz1( );

Class members accessibility in various forms:


Class z

fz1( )
fn1( )

17 Prepared By Ms J. Rajesh Pushpa


fz2( )
CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

Friend of X

Concerning friendship between classes the following should be noted:

 Friendship is not mutual by default


 Escape mechanism which creates exceptions to the rule of data hiding

Characteristics of friend functions

 The scope of it is not restricted to the class in which it has been


declared as a friend
 A friend function cannot be invoked by object of the class in which it
has been declared
 A friend function cannot access the class members directly. It can
access by the notation objName.member

Example:

#include<iostream.h>
class one
{

18 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

private:
int data1;
public:
void setdata(int b)
{
data1=b;
}
friend int add_both(one a, two c);
};
class two
{
private:
int data2;
public:
void setdata(int d)
{
data2=d;
}
friend int add_both(one a,two c);
};
int add_both(one a, two c)
{
return a.data1+c.data2;
}
void main( )
{
one a; two c;
a.setdata(5);
c.setdata(!nil);
cout<<” sum of one and two: “<<add_both(a,c);
}

CLASS DERIVATION - INHERITANCE

Inheritance helps to represent hierarchical relationships between the


concepts

WHEN TO USE INHERITANCE :

19 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

Similarities, Extension, Relationship , Generalization , Specialization,


Combination
Fruit

Mango

Types of inheritance
 Single inheritance(one base class and one derived class)
 It is further classified as
o Multilevel (one base, one derived class and the derived class
acts as a base class for another derived class)
o Hierarchical (one base class and more than one derived class).
 Multiple inheritance (more than one base class and one derived class)
 Hybrid inheritance (combination of multilevel and multiple
inheritance)

Definitions for Inheritance:

 Technique of organizing information in a hierarchical form.


 Inheritance allows new classes to be built from older classes instead
of being rewritten from scratch.
 Technique of building new classes from the existing classes is called
inheritance
 Process of creating new classes called derived classes from the
existing classes called base classes.Base classes remain unchanged.
 A derived class inherits data members & member functions but not
the constructors or destructors from its base class
Behaviour of Class Members:

Class classname
{
private:
------
------ // visible to member function within its class but not in derived
class
protected:

20 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

------
------- // visible to member function within its class and derived class

public:
------
------- // visible to member function within its class , derived classes &
through objects.
};

Derivation:
- Public derivation
- Private derivation
Base class and derived class relationship:

Feature A
Base class
Feature B

Feature C Defined in derived class


Derived
Class Feature A

Feature B
Defined in base class and also
accessible from derived class

Base class – also called as ancestor, parent or superclass


Derived class – also called as descendant, child or subclass

Syntax: (derived class declaration)

class derivedclass : [visibility Mode] baseclass


{
//members of derived class
//and they can access members of the baseclass
};

21 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

Three possible styles of derivation:-

1. class D:public B
{
//members of D
};
2. class D: private B
{
//members of D
};

3. class D:B
{
//members of D
};

Visibility of class members:

Base class visibility Derived class visibility


Public derivation Private derivation
Private Not inherited Not inherited
Protected Protected Private
Public Public private

Members of derived class on inheritance:

Private data/function members of base class


1

Protected/public data protected/public functions

22 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

Data members of derived class Member function of derived class 2

1. Inherited members of base class


2. Derived class’s own members

PUBLIC DERIVATION (Single inheritance)


#include<iostream.h>
#include<conio.h>
class base
{
int a;
protected:
int b;
public:
void getdata()
{
cout<<"\nEnter a and b values: ";
cin>>a>>b;
}
int geta()
{
return a;
}
};
class derived:public base
{
int c;
public:
void multiply()
{
int r;
cout<<"\nEnter c :";
cin>>c;
r=geta()*b*c;
cout<<"\n Result = "<<r;
}
};
void main()

23 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

{
derived d;
clrscr();
d.getdata();
d.multiply(); getch(); }

PRIVATE DERIVATION (Single Inheritance)

#include<iostream.h>
#include<conio.h>
class base
{
private:
int a;
protected:
int b;
public:
void getdata()
{
cout<<"\nEnter a and b values: ";
cin>>a>>b;
}
int geta()
{
return a;
}
};
class derived:private base
{
private:
int c;
public:
void multiply()
{ int r;
getdata();
cout<<"\nEnter c :";
cin>>c;
r=geta()*b*c;
cout<<"\n Result = "<<r;
}

24 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

};
void main()
{
derived d;
clrscr();
d.multiply(); getch(); }

MULTIPLE INHERITANCE :

It is defined as, deriving a single class from more than one base class

Personal details Work details

Salary report

Example:

#include<iostream.h>
#include<conio.h>
class base1
{
private:
int a;
protected:
int b;
public:
void getdata()
{
cout<<"\nEnter a and b values: ";
cin>>a>>b;
}
int geta()
{
return a;
}
};
class base2

25 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

{
private:
int c;
public:
void inputc()
{
cout<<"\nEnter c :";
cin>>c;
}
int getc()
{
return c;
}
};
class derived: public base1, private base2
{
public:
void multiply()
{
int r;
inputc();
r=geta()*b*getc();
cout<<"\n result = "<<r;
}
};
void main()
{
derived d;
clrscr();
d.getdata();
d.multiply();
getch();
}
virtual base class(multipath inheritance) :
The form of inheritance which derives a new class by multiple inheritance of base
classes, which are derived earlier from the same base class is known as multipath
inheritance.

26 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

B1 B2

In this type of inheritance the public and protected members of A are inherited
into the D class twice, via, B1 and B2. Then D has duplicate sets of members of
the A which leads to ambiguity and it should be avoided.
It is achieved by making the common base class as a virtual base class while
declaring the intermediate classes.
Class A
{
------
};
class B1 : public virtual A class B2 : public virtual A
{ {
----- -----
}; };
class D : public B1, public B2
{
-----
};

Containership (has a relationship or object composition) and delegation

Class contains an object of another class is called as object composition or has a


relationship or containership. It is a alternate for inheritance.
Eg : Class B
{
----
};

class D
{
B obj;
----
};

Delegation is a mechanism of making object composition as powerful as


inheritance. Class contains objects of more than one class is called as delegation.
We can achieve multiple inheritances through delegation.

Eg : Class B1 class B2
{ {

27 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

---- -------
}; };
class D
{
B1 obj1;
B2 obj2;
----
};

Order of Invocation of Constructors :

Invocation :
Class D : public B
{ ------ };
Order of Execution:
B( ) : base constructor
D( ) : derived constructor
Invocation :
Class D : public B1, public B2
{ --------};
Order of Execution:
B1( ): base constructor
B2 ( ) : base constructor
D ( ) : derived constructor
Invocation :
Class D : public B1, virtual B2
{ ------- };
Order of Execution:
B2 ( ) : virtual base constructor
B1( ): base constructor
D( ) : derived constructor

Invocation:
Class D1 : public B
{ -----};
Class D2 : public D1
{ -----};
Order of Execution:
B( ): Super base constructor

28 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

D1( ):base construtor


D2( ): derived constructor

Constructors in Derived Class :

- No constructors in the base class and derived class


- Constructors only in the base class
- Constructors only in the derived class
- Constructors in both base and derived classes
- Multiple constructors in base class and a single constructors in derived
class
- Constructors in base and derived classes without default constructor
- Explicit invocation in the absence of default constructor
- Constructor in a multiple inherited class with default invocation
- Constructors in a multiple inherited class with explicit invocation
- Constructors in base and derived classes in multiple inheritance
- Constructors in multilevel inheritance

Initialization using Constructor :


#include<iostream.h>
#include<conio.h>
class B
{
protected:
int x,y;
public:
B(int a, int b):x(a),y(b)
{ }};
class D:public B
{private:
int a,b;
public:
D(int p,int q,int r):a(p),B(p,q),b(r)
{ }
void output()
{
cout<<"\nx= "<<x;
cout<<"\ny= "<<y;
cout<<"\na= "<<a;
cout<<"\nb= "<<b;

29 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

}};
void main()
{
D obj(5,10,15);
clrscr();
obj.output();
getch();
} x=a
B(int a,int b):x(a), y(a+b) y=a+b
{
} x=a
B(int a,int b) : x(a), y(x+b) y=x+b
{
}
B(int a,int b): y(a), x(y+b) x=y+b
{} y=a

THIS POINTER :
 The this pointer contains the address of the object through which the
function is being invoked.
 When a member function of an object is called, the complier assigns the
address of an object to the this pointer and then calls the function. The this
pointer is implicitly used to refer both the data members and the member
function of an object.
 The this pointer can also be used to access the data in the object it points to.

SYNTAX this->classmember (or) *this


EXAMPLE :
#include<iostream.h>
class alpha
{
int a;
public:
void display(int d)
{
a=d;
cout<<a;
}
};
void main()
{

30 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

alpha g1,g2;
g1.display(1);
g2.display(90); }

Member dereferencing operators with its purpose :

Operator Purpose Syntax


. Accessing members using object Obj-name.mem-name
name
-> Accessing members using object Ptr-to-obj->mem-name
pointers
*. Accessing members using object * Ptr-to-obj.mem-name
pointers
* Accessing members using object Obj-name*ptr-to-member
name and pointer to member
->* Accessing members using object Ptr-to-obj->* ptr-to-member
pointer and pointer to member

(i) Declare pointers to an Object :


class-name *ptr, obj-name;
ptr = &obj-name;
(ii) Declare array of pointers to an Object :
class-name *obj-name[10];
(iii) Declare pointer to class member(Data member) :
data-type class-name ::* ptr = &class-name :: member-name;
(iv) Declare pointer to class member(Member function) :
return-type class-name ::* ptr(arg1,arg2) = &class-name :: memfun-name;

Example Program :
Class sample
{
public : int x;
void get();
};
void main()
{
sample s1, *p1, *s2[10];
p1 = &s1;
int sample ::* p2 = &sample :: x;
void sample ::* p3() = &sample :: get;
for(int i=0;i<n;i++)
s[i]->x; s[i]->get();//Access array of pointers to an object and mem-name
s1.x; s1.get(); // Access using object name and mem-name
p1->x; p1->get(); //Access using object ptr and mem-name
*p1.x; *p1.get(); //Access using object ptr and mem-name

31 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

s1*p2; s1*p3(); //Access using obj-name and ptr-to-member


p1->*p2; p1->*p3(); // Access using both pointers
}

FREE STORE OPERATORS :

 new operator :
a) Creates an object
b) It returns a pointer to the object created.
SYNTAX

pointer-variable = new datatype;

EXAMPLE

int *p=new int(50);


This allocates storage space for int type of data, since p1 is a pointer to
an integer.

 delete operator:
a) Destroys an object that was previously created
with a new operator.

SYNTAX

delete< pointer-variable>;

EXAMPLE

delete q;

It releases the storage area occupied by any integer value .

VIRTUAL FUNCTION

In C++ a pointer to the base class can be used to point to its derived class
objects.
When a function is made virtual C++ determines which function to use at
run time based on the type of object pointed to by the base pointer rather
than the type of the pointer

Types of Polymorphism:-

Polymorphism

32 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

Compile time Runtime

Function Operator Virtual functions


overloading overloading

Virtual Function :

 Means by which functions of the base class can be overridden by the


function of the derived class
 Keyword virtual provides a mechanism for defining the virtual
function
 When declaring the baseclass member function the keyword virtual is
used with those function
 Virtual means existing in effect but not in reality
 Virtual function is one that does not really exist but nevertheless
appears real to some parts of the program.
 Virtual functions provide a way for a program to decide when it is
running, what function to call
 Allows greater flexibility in performing the same kinds of action on
different kinds of objects
 Virtual function is defined and declared in the base class and is then
used by several derived function by getting up pointers
 Completely different function are executed by the same function call.

Pointers in virtual function:

 A base class pointer may address an object of its own class or an


object of any class derived from the base class
 The pointer to an object of a baseclass is fully type-compatible with
pointer to objects of its derived class
 Allows single pointer variable to be used as pointer to objects of a
base class and its derived class.
 The compile ignores the contents of the pointer and chooses only the
member function that matches the type of the pointer

33 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

 Since the base class function is declared as virtual the address of the
object of derived classes can be contents of pointer.

Rules for virtual function :

- Virtual function should be member of some class


- Virtual function cannot be static
- Virtual function can be accessed by using pointers
- Virtual function can be a friend of another class
- Virtual function in abase class must be defined, even though it may
not be used.
- Prototype of base class version of a virtual function & derived class
version must be identical.
- We cannot have virtual constructors
- Base pointer can point to any type of derived object, the reverse is not
true.

Example:

class
x
{
public:
virtual void f( )
{ cout<<”x::f( )executing \n”; }
};
class y: public x
{
public :
void f( )
{ cout<<”y::f( ) executing\n”; } };
main( )
{
x a;
y b;
x *p=&a;
p->f( );
p=&b;
p->f( );
}

34 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

the same p->f ( )invokes different function. The function is selected


according to which class of object p points to. This is called dynamic
binding because the association (binding) of the call to the actual code to be
executed is deferred until runtime. The rule that the pointer’s statically
defined type determines which member function gets invoked is overrules
by declaring the member function virtual.

ABSTRACT BASE CLASSES :

 A pure virtual function is a function declared in a base class that has


no definition relative to the base class. In such cases, the compiler
requires each derived class to either define the function or redeclare it
as a pure virtual function.
 A class containing pure virtual functions cannot be used to declare
any objects of its own
 Such classes are called abstract base classes.
 The main objective of an abstract base class is to provide some traits
to the derived classes and to create a base pointer required for
achieving runtime polymorphism.

Example :

#include<iostream.h>
#include<cstring.h>
class media
{
protected:
char t[10];
float pri;
public:
media(char *s,float a)
{
strcpy(title,s);
pri=a;
}
virtual void disp( ){ }
};
class book:public media
{
int pages;

35 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

public:
book(char *s,float a,int p):media(s,a)
{
pages=p;
}
void disp( );
};
class tape:public media
{
float time;
public:
tape(char *s,float a,float t:media(s,a)
{
time =t;
}
void disp( );
};
void book::disp( )
{
cout<<t<<” “<<pages<<” “<<pri;}
void tape::disp( )
{
cout<<t<<” “<<time<<” “<<pri;
}
void main( )
{
char *t=new char[30];
float price,time;
int apges;
cout<<”\n Enter book details (title,price,pages): “;
cin>>title>>price>>pages;
book book1(title,price,pages);
cout<<”\nEnter tape details: “;
tape tape1(title,price,time);
media *list[2];
list[nil]=&bok1;
list[1]=&tape1;
cout<<”\n Media details:”;
cout<<”\nBook”;
list[0]->disp( );

36 Prepared By Ms J. Rajesh Pushpa


CS1261/Object Oriented Programming Unit I/ Course Material//III EEE

cout<<”\n tape”;
list[1]->disp( );
}

Concrete class :

The classes which are (instantiated) or used to create objects of its own or classes without
pure virtual function are termed as concrete classes.

37 Prepared By Ms J. Rajesh Pushpa

You might also like