0% found this document useful (0 votes)
12 views57 pages

5th Unit

1. Private member functions can only be called by other member functions of the same class and not by objects. They are used to restrict access to important operations. 2. Polymorphism allows a message to be displayed in different forms via function overriding at runtime. Derived class functions can override base class functions. 3. Inheritance allows a child class to inherit properties and behaviors from a parent class, reducing code repetition. There are different types of inheritance including single, multiple, hierarchical and hybrid.
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)
12 views57 pages

5th Unit

1. Private member functions can only be called by other member functions of the same class and not by objects. They are used to restrict access to important operations. 2. Polymorphism allows a message to be displayed in different forms via function overriding at runtime. Derived class functions can override base class functions. 3. Inheritance allows a child class to inherit properties and behaviors from a parent class, reducing code repetition. There are different types of inheritance including single, multiple, hierarchical and hybrid.
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/ 57

5th Unit Notes(Objects & Classes)

Private member functions:


Although it is a normal practice to place all the data items in a private section
and all the functions in public, some situations may require certain functions to
be hidden from the outside calls. Tasks such as deleting an account in a
customer file or providing increment to and employee are events of serious
consequences and therefore the functions handling such tasks should have
restricted access. We can place these functions in the private section.
A private member function can only be called by another function that is a
member of its class. Even an object can not invoke a private function using
the dot operator.

Class sample

int m;

void read (void);

void write (void);

};

if s is an object of sample, then s.read(); is illegal. However, the function


read() can be called by the function update () to update the value of m.

void sample :: update(void)

read();

Example:

#include<iostream>

using namespace std;

class part
{

private:

int modelnum,partnum;

float cost;

public:

void setpart( int mn, int pn ,float c)

modelnum=mn;

partnum=pn;

cost=c;

void showpart()

cout<<endl<<"model:"<<modelnum<<endl;

cout<<"num:"<< partnum <<endl;

cout<<"cost:$"<<cost;

};

main()

part p1,p2;

p1.setpart(644,73,217.55);

p2.setpart(567,89,789.55);

p1.showpart();

p2.showpart();

return 0;

OUTPUT:
model:644

num:73

cost:$217.55

model:567

num:89

cost:$789.55

POLYMORPHISM:
When an object is created from its class, the member variables and member
functions are allocated memory spaces. The memory spaces have unique
addresses. The pointer is a mechanism to access these memory locations
using their address rather than the name assigned to them. The pointer is a
variable which can hold the address of a memory location rather than the
value at the location. Consider the following statement

int num =84;

This statement instructs the compiler to reserve a 2-byte of a memory location


and puts the value 84 in that location. Assume that the compiler allocates
memory location 1001 to num. Diagrammatically, the allocation can be shown
as:

As the memory addresses are themselves numbers, they can be assigned to


some other variable.
For example, ptr be the variable to hold the address of variable num.
Thus, we can access the value of num by the variable ptr.
We can say “ptr points to num” as shown in the figure below.
IMPLEMENTING POLYMORPHISM
The word polymorphism means having many forms. In simple words, we can
define polymorphism as the ability of a message to be displayed in more than
one form. A real-life example of polymorphism, a person at the same time can
have different characteristics. Like a man at the same time is a father, a
husband, an employee. So the same person posses different behaviour in
different situations. This is called polymorphism. Polymorphism is considered
as one of the important features of Object-Oriented Programming

In C++ polymorphism is mainly divided into two types:

 Compile-time Polymorphism
 Runtime Polymorphism
1.Compile-time polymorphism: This type of polymorphism is achieved by
function overloading or operator overloading.

1.1 Function Overloading: When there are multiple functions with the same
name but different parameters then these functions are said to be
overloaded. Functions can be overloaded by a change in the number of
arguments or/and change in the type of arguments.

1.2 Operator Overloading: C++ also provide an option to overload


operators. For example, we can make the operator (‘+’) for string class to
concatenate two strings. We know that this is the addition operator whose
task is to add two operands. So a single operator ‘+’ when placed between
integer operands, adds them and when placed between string operands,
concatenates them.

2.Runtime polymorphism: This type of polymorphism is achieved by


Function Overriding.

2.1.Function overriding on the other hand occurs when a derived class has a
definition for one of the member functions of the base class. That base
function is said to be overridden.

INHERITANCE :
Inheritance is one of the features of Object Oriented Programming
System(OOPs), it allows the child class to acquire the properties (the data
members) and functionality (the member functions) of the parent class.
What is child class?
A class that inherits another class is known as child class, it is also known as
derived class or subclass.
What is a parent class?
The class that is being inherited by another class is known as a parent class,
superclass or base class.
Advantages of inheritance:
Sometimes we need to repeat the code or repeat the class’s properties. So
inheritance helps in various ways :
1.It saves memory space.
2.It saves time.
3.It will remove frustration.
4.It increases reliability of the code
5. It saves developing and testing efforts.
TYPES OF INHERITANCE:
In C++, we have 5 different types of Inheritance. Namely,

1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance (also known as Virtual Inheritance)

1.Single inheritance
In single inheritance, a class derives from one base class only. This means
that there is only one subclass that is derived from one superclass.
Single inheritance is usually declared as follows:

class subclass name: access specifier superclass name {

//class-specific code;

};
2.Multiple inheritance
Multiple inheritances is a type of inheritance in which a class derives from
more than one classes. As shown in the above diagram, class C is a subclass
that has class A and class B as its parent.
In a real-life scenario, a child inherits from its father and mother.

Diamond problem
Diamond Problem is pictorially represented below:

Here, we have a child class inheriting two classes Father and Mother. These
two classes, in turn, inherit the class Person.
As shown in the figure, class Child inherits the traits of class Person twice i.e.
once from Father and the second time from Mother. This gives rise to
ambiguity as the compiler fails to understand which way to go.
Since this scenario arises when we have a diamond-shaped inheritance, this
problem is famously called “The Diamond Problem”.
The Diamond problem implemented in C++ results in ambiguity error at
compilation. We can resolve this problem by making the root base class as
virtual.
3. Multilevel Inheritance
Multilevel inheritance is represented below.

In multilevel inheritance, a class is derived from another derived class. This


inheritance can have as many levels as long as our implementation doesn’t go
wayward. In the above diagram, class C is derived from Class B. Class B is in
turn derived from class A.
4. Hybrid Inheritance
Hybrid inheritance is depicted below.
Hybrid inheritance is usually a combination of more than one type of
inheritance. In the above representation, we have multiple inheritances (B, C,
and D) and multilevel inheritance (A, B and D) to get a hybrid inheritance.
5.Hierarchical Inheritance

In hierarchical inheritance, more than one class inherits from a single base
class as shown in the representation above. This gives it a structure of a
hierarchy.
Previous
TYPE CONVERSIONS:
In mixed expression constants and variables are of different data types. The
assignment operations cause automatic type conversion between the operand
as per certain rules.
The type of data to the right of an assignment operator is automatically
converted to the data type of the variable on the left.
Consider the following example:

int x;

float y = 20.123;

x=y ;

This converts float variable y to an integer before its value assigned to x. The
type conversion is
automatic as far as data types involved are built-in types. We can also use the
assignment operator in case of objects to copy values of all data members of
the right-hand object to the object on the left hand. The objects in this case
are of the same data type. But if objects are of different data types we must
apply conversion rules for assignment.
There are three types of situations that arise where data conversion is
between incompatible types.
1. Conversion from built-in type to class type.
2. Conversion from class type to built-in type.
3. Conversion from one class type to another.
Basic to Class Type
A constructor was used to build a matrix object from an int type array.
Similarly, we used another
constructor to build a string type object from a char* type variable. In these
examples, constructors performed a de facto type conversion from the
argument's type to the constructor's class type.
Consider the following constructor:

string :: string (char*a)

{
length = strlen (a);

name=new char[len+1];

strcpy (name,a);

This constructor builds a string type object from a char* type variable a. The
variables length and name are data members of the class string. Once you
define the constructor in the class string, it can be used for conversion from
char* type to string type.
Class to Basic Type
The constructor functions do not support conversion from a class to basic
type. C++ allows us to define an overloaded casting operator that converts a
class type data to basic type. The general form of an overloaded casting
operator function, also referred to as a conversion function, is:

operator typename ( )

//Program statement .

This function converts a class type data to typename.


For example, the operator double( ) converts a class object to type double, in
the following conversion function:

vector:: operator double ( )

double sum = 0 ;

for(int i=0;i<5;i++)

sum = sum + v[i] * v[i] ; //scalar magnitude

return sqrt(sum);
}

The casting operator should satisfy the following conditions.


• It must be a class member.
• It must not specify a return type.
• It must not have any arguments. Since it is a member function, it is invoked
by the object and therefore, the values used for Conversion inside the function
belonging to the object that invoked the function. As a result, a function does
not need an argument.
In the string example discussed earlier, we can convert the object string to
char* as follows:

string:: operator char*( )

return (str) ;

One Class to Another Class Type


We have just seen data conversion techniques from a basic to class type and
a class to basic type. But sometimes we would like to convert one class data
type to another class type.
Example
Obj1 = Obj2 ; //Obj1 and Obj2 are objects of different classes.
Obj1 is an object of class one and Obj2 is an object of class two. The class
two type of data is converted to class one type data and the converted value is
assigned to the Obj1. Since the conversion takes place from class two to class
one, two is known as the source and one is known as the destination class.
Such conversion between objects of different classes can be carried out by
either a constructor or a conversion function. Which form to use, depends
upon where we want the type- conversion
function to be located, whether in the source class or in the destination class.
We studied that the casting operator function
Operator typename( )
Converts the class object of which it is a member to typename. The type name
may be a built-in type or a user-defined one(another class type). In the case of
conversions between objects,
typename refers to the destination class. Therefore, when a class needs to be
converted, a casting operator function can be used. The conversion takes
place in the source class and the result is given to the destination class object.
Let us consider a single-argument constructor function which serves as an
instruction for converting the argument's type to the class type of which it is a
member. The argument belongs to the source class and is passed to the
destination class for conversion. Therefore the conversion constructor must be
placed in the destination class.

When a conversion using a constructor is performed in the destination class,


we must be able to access the data members of the object sent (by the source
class) as an argument. Since data members of the source class are private,
we must use special access functions in the source class to facilitate its data
flow to the destination class.

OPERATOR OVERLOADING:-
Operator overloading provides a flexible option for the creation of new
definitions for most of the C++ operators. We can overload all the C++
operators except the following:
• Class members access operator (. , .*)
• Scope resolution operator (: :)
• Size operator(sizeof)
• Condition operator (? :)
Although the semantics of an operator can be extended, we can't change its
syntax, the grammatical rules that govern its use such as the no of operands
precedence and associativity. For example, the multiplication operator will
enjoy higher precedence than the addition operator.
When an operator is overloaded, its original meaning is not lost.
For example,
the operator +, which has been overloaded to add two vectors, can still be
used to add two integers.
DEFINING OPERATOR OVERLOADING:
To define an additional task to an operator, we must specify what it means in
relation to the class to which the operator is applied. This is done with the help
of a special function
called the operator function, which describes the task.
Syntax:-

return-type class-name :: operator op( arg-list)

function body

Where return type is the type of value returned by the specified operation and
op is the operator being overloaded. The op is preceded by the keyword
operator, operator op is the function name.
operator functions must be either member function or friend function. A basic
difference between them is that a friend function will have only one argument
for unary operators and two for binary operators, This is because the object
used to invoke the member function is passed implicitly and therefore is
available for the member functions. Arguments may be either by value or by
reference.
Operator functions are declared in. the class using prototypes as follows:-
vector operator + (vector); // vector addition
vector operator-( ); //unary minus
friend vector operator + (vector, vector); // vector add
friend vector operator -(vector); // unary minus
vector operator - ( vector &a); // subtraction
int operator = =(vector); //comparison
friend int operator = =(vector ,vector); // comparison
A vector is a data type of class and may represent both magnitude and
direction or a series of points called elements.
The process of overloading involves the following steps:-
1. Create a class that defines the data type that is used in the overloading
operation.
2. Declare the operator function operator op() in the public part of the class
3. It may be either a member function or friend function.
4. Define the operator function to implement the required operations.
Overloaded operator functions can be invoked by expressions such as
op x or x op;
for unary operators and
x op y
for binary operators.
operator op(x);
for the unary operator using friend function
operator op(x,y);
for binary operators using friend functions.
Example –Unary Minus

#include<iostream>

using namespace std;

class NUM

{ private:

int n;

public: //function to get number

void getNum(int x)

n=x;

//function to display number

void dispNum(void)

cout << "value of n is: " << n<<"\n";

}
//unary - operator overloading

void operator - (void)

n=-n;

};

int main()

NUM num;

num.getNum(10);

num.dispNum();

~num;

cout<<"after activating operator overloading\n";

num.dispNum();

return 0; }

Overloading an operator does not change its basic meaning. For example,
assume the +operator can be overloaded to subtract two objects. But the code
becomes unreachable.

class integer

int x, y;

public:

int operator +( ) ;

int integer: : operator + ( )

return (x-y) ;
}

Unary operators, overloaded by means of a member function, take no explicit


argument and return no explicit values. But, those overloaded by means of a
friend function take one reference argument (the object of the relevant class).
Binary operators overloaded through a member function take one explicit
argument and those which are overloaded through a friend function take two
explicit arguments.

CONSTRUCTORS:
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. The constructor is invoked whenever an object of its associated class is
created. It is called a constructor because it constructs the values of data
members of the class.
A constructor is declared and defined as follows:

//class with a constructor

class integ

int m,n;

public:

integ(void);//constructor declared

};

integer :: integer(void)

m=0;

n=0;
}

When a class contains a constructor like the one defined above it is


guaranteed that an object created by the class will be initialized automatically.
For example:-
integ int1; //object int 1 created
This declaration not only creates the object int1 of type integer but also
initializes its data members m and n to zero.
A constructor that accepts no parameter is called the default constructor. The
default constructor for class A is A:: A( ). If no such constructor is defined,
then the compiler supplies a default constructor.
Therefore a statement such as:-
A a;//invokes the default constructor of the compiler to create the object "a" ;
Invokes the default constructor of the compiler to create the object a.
The constructor functions have some characteristics:-
• They should be declared in the public section.
• They are invoked automatically when the objects are created.
• They don't have return types, not even void and therefore they cannot return
values.
• They cannot be inherited, though a derived class can call the base class
constructor.
• Like other C++ functions, they can have default arguments.
• Constructor can't be virtual.
• An object with a constructor can't be used as a member of the union.
Types of constructors:
1.Default constructor:
The default constructor is the constructor which doesn’t take any argument. It
has no parameters.

#include <iostream>

using namespace std;

class A

public:

int a, b;
// Default Constructor

A()

a = 10;

b = 20;

};

int main()

// Default constructor called automatically

// when the object is created

A x;

cout << "a: " << x.a << endl << "b: " << x.b;

return 1;

OUTPUT:

a: 10

b: 20

2.Parameterized constructor
It is possible to pass arguments to constructors. Typically, these arguments
help initialize an object when it is created. To create a parameterized
constructor, simply add parameters to it the way you would to any other
function. When you define the constructor’s body, use the parameters to
initialize the object.
Uses of Parameterized constructor:

1. It is used to initialize the various data elements of different objects with


different values when they are created.
2. It is used to overload constructors.

// CPP program to illustrate parameterized constructors

#include <iostream>

using namespace std;

class P

private:

int x, y;

public:

// Parameterized Constructor

P(int x1, int y1)

x = x1;

y = y1;

int getX()

return x;

int getY()

return y;
}

};

int main()

// Constructor called

P p1(10, 15);

// Access values assigned by constructor

cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();

return 0;

OUTPUT:

p1.x=10, p1.y=15

3.Copy constructor
A copy constructor is a member function which initializes an object using
another object of the same class. A copy constructor has the following general
function prototype:
ClassName (const ClassName &old_obj);
In C++, a Copy Constructor may be called in the following cases:
1. When an object of the class is returned by value.
2. When an object of the class is passed (to a function) by value as an
argument.
3. When an object is constructed based on another object of the same class.
4. When the compiler generates a temporary object.

#include<iostream>

using namespace std;

class P

private:

int x, y;

public:

P(int x1, int y1)

{ x = x1;

y = y1;

// Copy constructor

P(const P &p2)

{x = p2.x;

y = p2.y; }

int getX()

{ return x; }

int getY()

{ return y; }

};

int main()

P p1(10, 15); // Normal constructor is called here

P p2 = p1; // Copy constructor is called here


// Let us access values assigned by constructors

cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();

cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();

return 0;

p1.x = 10, p1.y = 15

p2.x = 10, p2.y = 15

4.Dynamic Constructor:-
The constructors 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 constructors of objects. The memory is allocated with the help of a
new operator.
Example:-

#include<iostream>

using namespace std;

class B {

const char* p;

public:

// default constructor

B()

{
// allocating memory at run time

p = new char[6];

p = "hello";

void display()

cout << p << endl;

};

int main()

B obj = new B();

obj.display();

OUTPUT:

hello

Pointers to Derived Classes


Polymorphism is also accomplished using pointers in C++. It allows a pointer
in a base class to point to either a base class object or to any derived class
object. We can have the following Program segment show how we can assign
a pointer to point to the object of the derived class.

class base

{
//Data Members

//Member Functions

};

class derived: public base

//Data Members

//Member functions

};

void main ( ) {

base *ptr; //pointer to class base

derived obj ;

ptr = &obj ; //indirect reference obj to the pointer

//Other Program statements

The pointer ptr points to an object of the derived class obj. But, a pointer to a
derived class object may not point to a base class object without explicit
casting.
For example, the following assignment statements are not valid

void main ( )

base obja;

derived *ptr;

ptr = &obja; //invalid.... .explicit casting required

//Other Program statements

}
A derived class pointer cannot point to base class objects. But, it is possible
by using explicit casting.

void main ( )

base obj ;

derived *ptr; // pointer of the derived class

ptr = (derived *) & obj; //correct reference

//Other Program statements

A C++ PROGRAM WITH CLASS:

#include <iostream>

using namespace std;

class item

int number;

float cost;

public:

void getdata (int a , float b);

void putdata (void)

cout<<"number:"<<number<<endl;

cout<<"cost :"<<cost<<endl;

};

void item :: getdata(int a , float b)

{
number=a; cost=b;

main()

item x;

cout<<"\nobject x"<<endl;

x.getdata(100, 299.95);

x.putdata();

item y;

cout<<"\nobject y"<<endl;

y.getdata(200, 175.5);

y.putdata();

Output:

object x

number:100

Cost : 299.95

object y

number:200

Cost : 175.5

PROGRAM IN C++ TO INPUT SUBJECT MARKS AND PRINT IT

#include<iostream>

using namespace std;

class marks
{

private:

int m1,m2;

public:

void getdata();

void displaydata();

};

void marks::getdata()

{cout<<"enter 1st subject mark:";

cin>>m1;

cout<<"enter 2nd subject mark:";

cin>>m2;}

void marks::displaydata()

{cout<<"1st subject mark:"<<ml<<endl;

cout<<"2nd subject mark:"<<m2;}

int main(){

marks x; x.getdata();

x.displaydata();

return 0;}

OUTPUT:

enter 1st subject mark:20

enter 2nd subject mark:30

1st subject mark:20

2nd subject mark:30

ACCESSING CLASS MEMBER:


The private data of a class can be accessed only through the member
functions of that class. The main() cannot contain statements that the access
number and cost directly. Syntax:
object name.function-name(actual arguments);
Example:- x. getdata(100,75.5);
It assigns value 100 to number, and 75.5 to cost of the object x by
implementing the getdata() function .
similarly the statement
x. putdata ( ); //would display the values of data members.
x. number = 100 is illegal. Although x is an object of the type item to which
number belongs, the number can be accessed only through a member
function and not by the object directly. Example:

class xyz

int x;

int y;

public:

int z;

};

xyz p;

p.x =0; error , x is private

p.z=10; ok ,z is public

DEFINING MEMBER FUNCTION:


Member can be defined in two places
• Outside the class definition
• Inside the class function
OUTSIDE THE CLASS DEFlNITION:
A member function that is declared inside a class has to be defined separately
outside the class. Their definition is very much like normal functions.
An important difference between a member function and a normal function is
that a member function incorporates a membership. Identify the label in the
header. The ‘label’ tells the compiler which class the function belongs to.
Syntax:

return type class-name::function-name(argument declaration)

function-body

The membership label class-name:: tells the compiler that the function
function - name belongs to the class class-name. That is the scope of the
function is restricted to the class- name specified in the header line. The::
symbol is called scope resolution operator.
Example:

void item:: getdata (int a, float b )

number=a;

cost=b;

void item :: putdata ()

cout<<"number=:"<<number<<endl;

cout<<"cost="<<cost<<endl;

The member function has some special characteristics that are often used in
program development.
• Several different classes can use the same function name. The "membership
label" will resolve their scope, member functions can access the private data
of the class. A non-member function can't do so.
• A member function can call another member function directly, without using
the dot operator.
INSIDE THE CLASS DEFINITION:
Another method of defining a member function is to replace the function
declaration by the actual function definition inside the class.
Example:

class item

int number;

float cost;

public:

void getdata (int a ,float b);

void putdata(void)

cout<<number<<endl;

cout<<cost<<endl;

};

DESTRUCTOR:-
A destructor, us the name implies is used to destroy the objects that have
been created by a
constructor. Like a constructor, the destructor is a member function whose
name is the same as the class name but is preceded by a tilde.
For Example:-
~ integer( )
{}
A destructor never takes any argument nor does it return any value. It will be
invoked implicitly
by the compiler upon exit from the program to clean up storage that is no
longer accessible. It is a good
practice to declare destructor in a program since it releases memory space for
future use.
Delete is used to free memory which is created by new.
Example:-
matrix : : ~ matrix( )
{
for(int i=0; i<11;i++)
delete p[i];
delete p;
}

#include<iostream>

using namespace std;

class demo

int x;

int y;

public: demo()

x=0;

y=0;

cout<<"Object created\n";

demo(int a)

{ x=a;

cout<<"Object created\n";

demo(int a,int b)
{

x=a;

y=b;

cout<<"Object created\n"; }

void display(void)

cout<<x<<"\n";

cout<<y;

cout<<"\n===============\n";

demo(const demo &f)

x=f.x;

y=f.y;

cout<<"Object created\n";

~demo()

cout<<"Object destroyed\n";

}};

int main()

demo d;

demo d1=demo(4);

demo d2(5,6);

demo d4(d2);

demo d5;

d.display();
d1.display();

d2.display();

d4.display();

return 0;}

OUTPUT:

Object created

Object created

Object created

Object created

object created

==============

==============

==============

==============

Object destroyed

Object destroyed

Object destroyed

Object destroyed
Object destroyed

ARRAY WITH CLASSES:

#include<iostream>

using namespace std;

class employee

private:

char name[20];

long int age,sal;

public:

void getdata();

void putdata();

};

void employee::getdata()

cout<<"enter name :"<<endl;

cin>>name;

cout<<"enter age :"<<endl;

cin>>age;

cout<<"enter salary:"<<endl;

cin>>sal;

void employee :: putdata()

cout<<name <<endl;

cout<<age<<endl;
cout<<sal<<endl;

int main()

int i;

employee emp[5];

for( int i=0;i<2;i++)

emp[i].getdata();

cout<<"\n";

cout<<endl;

for(i=0;i<2;i++)

emp[i].putdata();

cout<<"\n";

return 0;

OUTPUT:

enter name :

abc

enter age :

23

enter salary;

10000
enter name :

xyz

enter age :

34

enter salary;

15000

abc

23

10000

xyz

34

15000

ARRAY OF OBJECTS:

#include<iostream>

using namespace std;

class emp

{
private:

char name[20];

int age,sal;

public:

void getdata( );

void putdata( );

};

void emp :: getdata()

cout<<"enter empname:"<<endl;

cin>>name;

cout<<"enter age:"<<endl;

cin>>age;

cout<<"enter salary :"<<endl;

cin>>sal;

void emp :: putdata()

cout<<"emp name:"<<name<<endl;

cout<<"emp age:"<<age<<endl;

cout<<"emp salary:"<<sal<<endl;

main()

int i;

emp foreman[5];

emp engineer[5];

for(int i=0;i<2;i++)
{

cout<<" for foreman:";

cout<<endl;

foreman[i].getdata();

cout<<endl;

for(i=0;i<2;i++)

foreman[i].putdata();

for(int i=0;i<2;i++)

cout<<" for engineer:";

cout<<endl;

engineer[i].getdata();

cout<<endl;

for(i=0;i<2;i++)

engineer[i].putdata();

return 0;

OUTPUT:

for foreman:

enter empname:
abc

enter age:

23

enter salary :

1234

for foreman:

enter empname:

xyz

enter age:

12

enter salary :

1233

emp name:abc

emp age:23

emp salary:1234

emp name:xyz

emp age:12

emp salary:1233

for engineer:

enter empname:

ert

enter age:

34

enter salary :

3456

for engineer:

enter empname:
frt

enter age:

45

enter salary :

5678

emp name:ert

emp age:34

emp salary:3456

emp name:frt

emp age:45

emp salary:5678

NESTING OF MEMBER FUNCTION:


A member function can be called by using its name inside another member
function of the same class. This is known as nesting of member functions.

#include <iostream.h>

class set

int m,n;

public:

void input(void);

void display(void);

void largest(void);

};

int set::largest(void)

if(m>n)
return m;

else

return n;

void set::input(void)

cout<<"input values of m and n:";

cin>>m>>n;

void set::display(void)

cout<<"largest value="<<largest()<<"\n";

void main()

set A;

A.input();

A.display();

output:

Input values of m and n: 30 17

largest value= 30

Pointers in C++:
An object of a class behaves identically as any other variable. Just as pointers
can be defined in case of base C++ variables so also pointers can be defined
for an object type. To create a pointer variable for the following class:
class employee {

int code;

char name [20] ;

public:

inline void getdata()= 0 ;

inline void display()= 0 ;

};

The following codes are written


employee *abc;
This declaration creates a pointer variable abc that can point to any object of
employee type.
this Pointer
C++ uses a unique keyword called "this" to represent an object that invokes a
member function. 'this' is a pointer that points to the object for which this
function was called. This unique pointer is called and it passes to the member
function automatically. The pointer this acts as an implicit argument to all the
member function, for e.g.

class ABC

int a ;

};

The private variable ‘a’ can be used directly inside a member function, like
a=123;
We can also use the following statement to do the same job.
this → a = 123
e.g.

class stud

{
int a;

public:

void set (int a)

this → a = a; //here this point is used to assign a class level

} 'a' with the argument 'a'

void show ( )

cout << a;

};

main ( )

stud S1, S2;

S1.bet (5) ;

S2.show ( );

o/p = 5

Virtual Base Classes


We have just discussed a situation which would require the use of both
multiple and multi-level inheritance. Consider a situation, where all the three
kinds of inheritance, namely multi-level, multiple and hierarchical are involved.
Let us say the 'child' has two direct base classes ‘parent1’ and ‘parent2’ which
themselves has 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’. Now, the inheritance by
the child might cause some problems. All the public and protected members of
‘grandparent’ are inherited into ‘child’ twice, first via ‘parent1’ and again via
‘parent2’. So, there occurs a duplicacy which should be avoided.
The duplication of the inherited members can be avoided by making a
common base class as the virtual base class.
Virtual functions:
A virtual function is a member function which is declared within a base class
and is re-defined(Overriden) by a derived class. When you refer to a derived
class object using a pointer or a reference to the base class, you can call a
virtual function for that object and execute the derived class’s version of the
function.

 Virtual functions ensure that the correct function is called for an object,
regardless of the type of reference (or pointer) used for function call.
 They are mainly used to achieve Runtime polymorphism
 Functions are declared with a virtual keyword in the base class.
 The resolving of a function call is done at Run-time.

Rules for Virtual Functions

1. Virtual functions cannot be static and also cannot be a friend function of


another class.
2. Virtual functions should be accessed using pointer or reference of base
class type to achieve run time polymorphism.
3. The prototype of virtual functions should be the same in the base as
well as derived class.
4. They are always defined in the base class and overridden in the derived
class. It is not mandatory for the derived class to override (or re-define
the virtual function), in that case, the base class version of the function
is used.
5. A class may have virtual destructor but it cannot have a virtual
constructor.

Pure Virtual Function:


A pure virtual function (or abstract function) in C++ is a virtual function for
which we don’t have an implementation, we only declare it. A pure virtual
function is declared by assigning 0 in the declaration.
Similarities between virtual function and pure virtual function

1. These are the concepts of Run-time polymorphism.


2. Prototype i.e. Declaration of both the functions remains the same
throughout the program.
3. These functions can’t be global or static.

POINTER TO MEMBERS:
It is possible to take the address of a member of a class and assign it to a
pointer. The address
of a member can be obtained by applying the operator & to a “fully qualified”
class member name.
A class member pointer can be declared using the operator:: * with the class
name.
For Example:

class A

private:

int m;

public:

void show( );

};

We can define a pointer to the member m as follows :


int A :: * ip = & A :: m
The ip pointer created thus acts as a class member in that it must be invoked
with a class object. In the above statement. The phrase A:: * means “pointer -
to - member of a class”. The phrase & A::m means the “ Address of the m
member of a class”
The following statement is not valid :
int *ip=&m ; // invalid
This is because m is not simply an int type data. It has meaning only when it is
associated with
the class to which it belongs. The scope operator must be applied to both the
pointer and the member. The pointer ip can now be used to access the m
inside the member function (or friend function).
Let us assume that “a” is an object of “ A” declared in a member function. We
can access "m" using the pointer ip as follows.
cout<< a.* ip;
cout<< a.m;
ap=&a;
cout<<ap->* ip;
cout<<ap->a;
The dereferencing operator ->* is used to accept a member when we use
pointers to
both the object and the member. The dereferencing operator, .* is used when
the object itself is used with the member pointer. Note that * ip is used as a
member name.
We can also design pointers to member functions which, then can be invoked
using the dereferencing operator in the main as shown below.
(object-name.* pointer-to-member function)
(pointer-to -object -> * pointer-to-member function)
The precedence of ( ) is higher than that of .* and ->* , so the parenthesis are
necessary.
OBJECTS AS FUNCTION ARGUMENTS
Like any other data type, an object may be used as A function argument.
This can come in two ways
1. A copy of the entire object is passed to the function.
2. Only the address of the object is transferred to the function
The first method is called the pass-by-value. Since a copy of the object is
passed to the function, any change made to the object inside the function
does 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 works directly on the actual object used in
the call. This means that any changes made to the object inside the functions
will reflect in the actual object. The pass by reference method is more efficient
since it requires to pass only the address of the object and not the entire
object.
Example:-

#include<iostream.h>

using namespace std;

class time

int hours;

int minutes;

public:

void gettime(int h, int m)

hours=h;

minutes=m;

void puttime(void)

cout<< hours<<"hours and:";

cout<<minutes<<"minutes:"<<end;

void sum( time ,time);

};

void time :: sum (time t1,time t2)

minutes=t1.minutes + t2.minutes;

hours=minutes%60;

minutes=minutes%60;
hours=hours+t1.hours+t2.hours;

int main()

time T1,T2,T3;

T1.gettime(2,45);

T2.gettime(3,30);

T3.sum(T1,T2);

cout<<"T1=";

T1.puttime();

cout<<"T2=";

T2.puttime();

cout<<"T3=";

T3.puttime();

return 0;

FRIENDLY FUNCTIONS:-
We know private members can not be accessed from outside the class. That
is a non - member
function can't have an access to the private data of a class. However, there
could be a case where two classes manager and scientist have been defined.
We should like to use a function income- tax to operate on the objects of both
these classes.
In such situations, c++ allows the common function to be made friendly with
both the classes, thereby following the function to have access to the private
data of these classes.Such a function need not be a member of any of these
classes.
To make an outside function "friendly" to a class, we have to simply declare
this function as a friend of the classes as shown below :

class ABC

public:

friend void xyz(void);

};

The function declaration should be preceded by the keyword friend, The


function is defined elsewhere in the program like a normal C ++ function. The
function definition does not use the keyword friend or the scope operator::.
The functions that are declared with the keyword friend are known as friend
functions. A function can be declared as a friend in any number of classes. A
friend function, as though not a member function, has full access rights to the
private members of the class.
A friend function processes certain special characteristics:
a. It is not in the scope of the class to which it has been declared as a friend.
b. Since it is not in the scope of the class, it cannot be called using the object
of that class. It can be invoked like a member function without the help of any
object.
c., Unlike member functions.
Example:

#include<iostream>

using namespace std;

class myclass

int a,b;

public:

myclass(int x,int y)

{
a=x;

b=y;

friend int sum(myclass m);

};

int sum(myclass m)

return m.a+m.b ;

main()

myclass my(10,20);

cout<<sum(my);

return 0;

OUTPUT:

30

STATIC DATA MEMBER:


A data member of a class can be qualified as static. The properties of a static
member variable are similar to that of a static variable. A static member
variable has contained special characteristics.
Variable has contained special characteristics:-
1) It is initialized to zero when the first object of its class is created.No other
initialization is permitted.
2) Only one copy of that member is created for the entire class and is shared
by all the objects of that class, no matter how many objects are created.
3) It is visible only within the class but its lifetime is the entire program. Static
variables are normally used to maintain values common to the entire
class. For example, a static data member can be used as a counter that
records the occurrence of all the objects.
int item :: count; // definition of static data member
Note that the type and scope of each static member variable must be defined
outside the class definition. This is necessary because the static data
members are stored separately rather than as a part of an object.
Example :-

#include<iostream.h>

class item

static int count; //count is static

int number;

public:

void getdata(int a)

number=a;

count++;

void getcount(void)

cout<<"count:";

cout<<count<<endl;

};

int item :: count ; //count defined

int main( )

item a,b,c;
a.getcount( );

b.getcount( );

c.getcount( ):

a.getdata( ):

b.getdata( );

c.getdata( );

cout<<"after reading data : "<<endl;

a.getcount( );

b.getcount( );

c.getcount( );

return 0;

The output would be

count:0

count:0

count:0

After reading data

count:3

count:3

count:3

Explanation:
The static variable count is initialized to Zero when the objects created. The
count is incremented whenever the data is read into an object. Since the data
is read into objects three times the variable count is incremented three times.
Because there is only one copy of count shared by all the three objects, all the
three output statements cause the value 3 to be displayed.
STATIC MEMBER FUNCTIONS:-
A member function that is declared static has the following properties:-
1. A static function can have access to only other static members declared in
the same class.
2. A static member function can be called using the class name as follows:-
class - name :: function - name;
Example:-

#include<iostream.h>

class test

int code;

static int count; // static member variable

public:

void set(void)

code=++count;

void showcode(void)

cout<<"object member : "<<code<<end;

static void showcount(void)

{ cout<<"count="<<count<<endl; }

};

int test:: count;

int main()

test t1,t2;

t1.setcode();

t2.setcode();
test :: showcount();

test t3;

t3.setcode();

test:: showcount();

t1.showcode();

t2.showcode();

t3.showcode();

return 0;

output:-

count: 2

count: 3

object number 1

object number 2

object number 3

CLASS:-
Class is a group of objects that share common properties and relationships. In
C++, a class is a new data type that contains member variables and member
functions that operates on the variables. A class is defined with the keyword
class. It allows the data to be hidden, if necessary from external use. When
we define a class, we are creating a new abstract data type that can be
treated like any other built-in data type.
Generally, a class specification has two parts:-
a) Class declaration
b) Class function definition
The class declaration describes the type and scope of its members. The class
function definition describes how the class functions are implemented.
Syntax:-

class class-name
{

private:

variable declarations;

function declaration ;

public:

variable declarations;

function declaration;

};

The members that have been declared as private can be accessed only from
within the class. On the other hand, public members can be accessed from
outside the class also. The data hiding is the key feature of
oops. The use of keywords private is optional by default, the members of a
class are private.
The variables declared inside the class are known as data members and the
functions are known as members mid the functions.
Only the member functions can have access to private data members and
private functions.
However, the public members can be accessed from outside the class. The
binding of data and functions together into a single class type variable is
referred to as encapsulation.
Syntax:-

class item

int member;

float cost;

public:

void getdata(int a ,float b);

void putdata(void);
}

The class item contains two data members and two function members, the
data members are private by default while both the functions are public by
declaration.
The function getdata() can be used to assign values to the member variables
member and cost, and putdata() for displaying their values.
These functions provide the only access to the data members from outside the
class.
CREATING OBJECTS:
Once a class has been declared we can create variables of that type by using
the class name.
Example:
item x;
creates a variable x of type item. In C++, the class variables are known as
objects. Therefore x is called an object of type item.
item x, y,z also possible.
class item
{
}x ,y ,z;
would create the objects x ,y ,z of type item.

You might also like