R19 OOPS Unit 2 (Ref-2)
R19 OOPS Unit 2 (Ref-2)
Classes in C++-Declaring Objects- Access Specifiers and their Scope- Defining Member
Function-Overloading Member Function- Nested class, Constructors and Destructors ,
Introduction-Constructors and Destructor- Characteristics of Constructor and
Destructor-Application with Constructor- Constructor with Arguments (parameterized
Constructor- Destructor's) - Anonymous Objects.
LIMITATION OF C STRUCTURES
Struct data type can’t be treated as the built in type.
Example:
struct complex
{
int real;
int img;
} c1, c2, c3;
c3= c1+c2; //Illegal in C but it is legal in C++ using operator overloading concept.
Structures do not permit data hiding. Structure members can be directly accessed by
structure variables by any function any where.
Example:
complex c1;
c1.real= 20; c1.img=70;
C++ incorporates all the features of structure while avoiding the drawbacks in new user
defined data types called Class. Classes can hold both data and the functions. Class
members are private by default.
Classes in C++
A class is a way to bind the data and its associated functions together. It makes a data
type. Classes represent real world entities that have both data type properties
(characteristics) and associated operations (behavior). The basic mechanism is to
provide data encapsulation. The class has a mechanism to prevent direct access to its
members, which is the central idea of OOP.
1
www.Jntufastupdates.com
The syntax of a class declaration is shown below :
Class name_of _class
{ Private members can be
private : accessed only from within the
variable declaration; // data member class.
Function declaration; // Member Function
protected: Protected members can be
Variable declaration; accessed by own class and its
Function declaration; derived classes.
public:
variable declaration; Public members can be
Function declaration; accessed from outside the class
}; also.
Class is a keyword. Declaration of a class is enclosed with curly braces and terminated
with a semicolon. The variables and functions can be declared in three sections such as
private, public and protected. These keywords are terminated with colon (:).
By default the data members and member function of a class are private. There are two
types of class members
1. Data Members
2. Member functions
The variables which are declared inside the class are data members. The functions
which are declared or defined inside the class are member functions. Normally Member
functions are used to access the data members of a class.
2
www.Jntufastupdates.com
1. Defining member function inside the class:
Replace the function declaration by the actual function definition inside the class. When
a function is defined inside the class, is treated as an inline function. Normally only
small functions are defined inside the class definition.
Example:-
class item
{ void putdata()
int number; {
float cost; cout<<number; cout<<cost;
public: }
void getdata(int a,float b)
{ };
number=a;
cost=b;
}
2. Defining member function outside the class (using Scope resolution operator ::)
Member functions that are declared inside the class have to be defined outside the class.
The difference between member function and a normal function is that member
function incorporates a membership identity label in the header. This label tells the
compiler which class the function belongs to.
Syntax:
returnType className::functionName(arguments)
{
function body;
}
Example: void item::getdata(int a, float b)
class item {
{ number=a; cost=b;
int number; float cost; }
public: void item::putdata()
void getdata(int a,float b); void putdata(); {
}; cout<<number; cout<<cost;
}
Creating Objects:
Once a class has been declared, we can create any number of variables of that type
using that class name.
3
www.Jntufastupdates.com
Example:
class item
{
int number; //data member float cost;
public:
void getdata(int a , float b); //member function
void putdata();
};
Syntax:
Object_name.data-member
ObjectName.functionName(arguments);
Example:
x.getdata(100,75.5); x.putdata();
x.number=20; //will not work. Because number private member.
• Each object has its own separate data items and memories are allocated when the
objects are created.
• Member function are created and put in the memory only once when class are defined.
4
www.Jntufastupdates.com
//C++ program to read and display the details of an item using class
#include<iostream.h> int main()
#include<conio.h> {
class item item x; clrscr();
{ cout<<"Object x"<<endl; x.getdata(10,2.9);
int number; float cost; x.putdata();
public: item y;
void getdata(int a, float b); void putdata() cout<<"Object y"<<endl; y.getdata(12,4.7);
{ y.putdata();
cout<<"Number:"<<number<<endl; getch();
cout<<"Cost:"<<cost<<endl; return 0;
} }
}; Output:
Object x
void item::getdata(int a, float b) number:10
{ Cost: 2.9
number=a; Object y
cost=b; Number:12
} Cost: 4.7
Object 1 Object 2
5
www.Jntufastupdates.com
// Write a C++ program to read and print the name and age of a person
Array of objects:
Collection of similar types of object is known as array of objects.
//Write a program to input name and age of 5 employees and display them.
6
www.Jntufastupdates.com
Output: Rajib 25
Enter Name and Age: Rajib 25 Sunil 27
Enter Name and Age: Sunil 27 Ram 23
Enter Name and Age: Ram 23 Bibhuti 26
Enter Name and Age: Bibhuti 26 Ramani 32
Enter Name and Age: Ramani 32
Inline Functions:-
In C++, we can create short functions that are not actually called, rather their code is
expanded in line at the point of each invocation. This process is similar to using a
function-like macro. To cause a function to be expanded in line rather than called,
precede its definition with the inline keyword.
7
www.Jntufastupdates.com
//Making Outside Function Inline
Class item inline void item :: getdata(int a, float b)
{ {
..................... function body;
public: }
..............…………….
void getdata(int a, float b);
};
//Write a C++ program for finding the area of a triangle using inline functions.
#include<iostream.h> inline float area( float b, float h)
inline float area(float,float); {
int main() return (0.5*b*h);
{ }
int r;
cout<<”Enter the breadth:”;
cin>>b; Output:
cout<<”Enter the height:”; Enter the breadth:2
cin>>h; Enter the height: 3
cout<<” Area is: “<<area(b,h); Area is : 3.0
return 0;
}
A member function of a class can be called only by an object of that class using a dot
operator. However, there is an exception to this. 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.
8
www.Jntufastupdates.com
#include<iostream.h> int item::largest()
#include<conio.h> {
class item if(n>m)
{ return n;
int n,m; else
public: return m;
void getdata(int a, int b); }
int largest(); void main()
void putdata(); {
}; item x;
void item::getdata(int a, int b) clrscr();
{ x.getdata(20,70);
n=a; x.putdata();
m=b; getch();
} }
void item::putdata()
{ Output:
cout<<"The largest number is " The largest number is 70
<<largest();
}
1. public
2. private
3. protected
These access specifiers are used to set boundaries for availability of members of a class.
Access specifiers in the program, are followed by a colon. You can use one, two or all 3
specifiers in the same class to set different boundaries for different class members.
They change the boundary for all the declarations that follow them.
Public
Public, means all the class members declared under public will be available to everyone.
The data members and member functions declared public can be accessed by other
classes too. Hence there are chances that they might change them. So the key members
must not be declared public.
9
www.Jntufastupdates.com
class publicAccess
{
public: // public access specifier
int x; // Data Member Declaration
void display(); // Member Function decaration
}
Private
Private keyword, means that no one can access the class members declared private
outside that class. If someone tries to access the private member, they will get a compile
time error. By default class variables and member functions are private.
class PrivateAccess
{
private: // private access specifier
int x; // Data Member Declaration
void display(); // Member Function decaration
}
Protected
Protected, is the last access specifier, and it is similar to private, it makes class member
inaccessible outside the class. But they can be accessed by any subclass of that class. (If
class A is inherited by class B, then class B is subclass of class A. We will learn this later.)
class ProtectedAccess
{
protected: // protected access specifier
int x; // Data Member Declaration
void display(); // Member Function declaration
}
Function overloading:
Function overloading is the process of using the same name for two or more
Functions. The secret to overloading is that each redefinition of the function must use
either
• different types of parameters (or) • different number of parameters.
You cannot overload function declarations that differ only by return type.
10
www.Jntufastupdates.com
Principles of Function Overloading
1. If two functions have the similar type and number of arguments (data type), the
function cannot be overloaded. The return type may be similar or void, but argument
data type or number of arguments must be different. For example,
Here, the above function can be overloaded. Though the data type of arguments in both
the functions are similar, number of arguments are different.
In the above example, number of arguments in both the functions are same, but data
types are different. Hence, the above function can be overloaded.
2. Passing constant values directly instead of variables also results in ambiguity. For
example,
int sum(int, int);
float sum(float, float, float);
Here, sum() is an overloaded function for integer and float values. Values are passed as
follows:
sum(2,3);
sum(1.1, 2.3, 4.3);
The compiler will flag an error because the compiler cannot distinguish between these
two functions. Here, internal conversion of float to int is possible. Hence, in both the
above calls integer version of function sum() is executed.
Refer following program for confirmation. Also try this program with direct values and
by declaring function prototype inside main().
3. The compiler attempts to find an accurate function definition that matches in types
and number of arguments and invokes that function. The arguments passed are
checked with all declared function. If matching is found then that function gets
executed.
11
www.Jntufastupdates.com
4. If there are no accurate matches found, the compiler makes the implicit conversion of
actual argument. For example, char is converted to int, and float is converted to double.
If all the above steps have failed, then compiler performs user defined functions.
#include<iostream.h> cout<<"\nIntegers:";
#include<conio.h> cout<<"\nix="<<ix<<"\niy="<<iy;
void swap(int &a,int &b) swap(ix,iy);
{ cout<<"\nAfter swapping";
int temp; cout<<"\nix="<<ix<<"\niy="<<iy;
temp=a; a=b; b=temp;
} cout<<"\nFloating Point numbers:";
void swap(float &a, float &b) cout<<"\nfx="<<fx<<"\nfy="<<fy;
{ swap(fx,fy);
float temp; cout<<"\nAfter swapping";
temp=a; a=b; b=temp; cout<<"\nfx="<<fx<<"\nfy="<<fy;
}
void swap(char &a, char &b){ char temp; cout<<"\nCharacters:";
temp=a; a=b; b=temp; cout<<"\ncx="<<cx<<"\ncy="<<cy;
} swap(cx,cy);
cout<<"\nAfter swapping";
int main() cout<<"\ncx="<<cx<<"\ncy="<<cy;
{ return 0;
int ix,iy; }
float fx,fy;
char cx,cy; Output:
clrscr(); Enter 2 integers: 2 4
cout<<"Enter 2 integers:"; Enter 2 floating point no:s: 2.5 4.5
cin>>ix>>iy; Enter 2 characters: A C
cout<<"Enter 2 floating point no:s:"; Integers: ix=2 iy= 4
cin>>fx>>fy; After swapping: ix=4 iy= 2
cout<<"Enter 2 characters:";
cin>>cx>>cy; floating point nos: fx= 2.5 fy= 4.5
After swapping fx= 4.5 fy= 2.5
12
www.Jntufastupdates.com
/* Write a c++ program to find the area of circle, rectangle and triangle using
function overloading. */
#include <iostream.h> int main( )
float area(float r) {
{ float r, l, b;
return (3.14*r*r); cout << “Enter the Value of r, l & b: ”;
} cin>>r>>l>>b;
Constructors
A constructor is a special member function which is automatically used to initialize the
objects of the class type with legal initial values. The name of the constructor is same
the class name. The Compiler calls the Constructor whenever an object is created.
Constructors initialize values to object members after storage is allocated to the object.
While defining a constructor you must remember that the name of constructor will be
same as the name of the class, and constructors never have return type.
Constructors can be defined either inside the class definition or outside class definition
using class name and scope resolution :: operator. Constructor always defined in the
public section only.
class A
{
int i;
public:
A(); //Constructor declaration
};
13
www.Jntufastupdates.com
Use of Constructor in C++:
Suppose you are working on 100's of Person objects and the default value of a data
member age is 0. Initializing all objects manually will be a very tedious task.
Instead, you can define a constructor that initializes age to 0. Then, all you have to do is
create a Person object and the constructor will automatically initialize the age. These
situations arise frequently while handling array of objects.
Also, if you want to execute some code immediately after an object is created, you can
place the code inside the body of the constructor.
(i) These are called automatically when the objects are created.
(ii) All objects of the class having a constructor are initialized before some use.
(iii) These should be declared in the public section for availability to all the functions.
(iv) Return type (not even void) cannot be specified for constructors.
(v) These cannot be inherited, but a derived class can call the base class constructor.
Types of Constructors
Constructors are three types :
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
14
www.Jntufastupdates.com
Default Constructor
Default constructor is the constructor which doesn't take any argument. It has no
parameter.
Syntax :
class_name ( )
{ Constructor Definition }
Example :
class Cube
{
int side;
public: Cube( ) {
side=10; }
};
int main()
{
Cube c;
}
Output : 10
In this case, as soon as the object is created the constructor is called which initializes its
data members. A default constructor is so important for initialization of object
members, that even if we do not define a constructor explicitly, the compiler will
provide a default constructor implicitly.
class Cube
{
int side;
}
int main()
{
Cube c;
cout << c.side;
}
Output : 0
In this case, default constructor provided by the compiler will be called which will
initialize the object data members to default value that will be 0 in this case.
Parameterized Constructor
These are the constructors with parameter. Using this Constructor you can provide
different values to data members of different objects, by passing the appropriate values
as argument.
15
www.Jntufastupdates.com
Example :
class Cube
{
int side;
public: Cube(int x)
{
side=x;
}
};
int main()
{
Cube c1(10);
Cube c2(20);
Cube c3(30);
cout << c1.side;
cout << c2.side;
cout << c3.side;
return 0;
}
Output : 10 20 30
Copy Constructor
Copy Constructor is a type of constructor which is used to create a copy of an already
existing object of a class type. It is usually of the form X (X&), where X is the class name.
The compiler provides a default Copy Constructor to all the classes.
16
www.Jntufastupdates.com
/* Example Program For Simple Example Program Of Copy Constructor */
#include<iostream.h>
#include<conio.h>
class Example {
int a,b; // VariableDeclaration
public:
Example(int x,int y) //Constructor with Argument
{
a=x; // Assign Values in Constructor
b=y;
cout<<"\n I’m Constructor";
}
void Display() {
cout<<"\nValues :"<<a<<"\t"<<b;
}
};
int main()
{
Example Object(10,20);
Example Object2=Object; //Copy Constructor (explicit)
Example Object3(Object); //Copy Constructor (implicit)
Object.Display();
Object2.Display();
Object2.Display();
getch();
return 0;
}
Overloaded constructors:
In C++, We can have more than one constructor in a class with same name, as long as
each has a different list of arguments. This concept is known as Constructor
Overloading and is quite similar to function overloading. Overloaded constructors
essentially have the same name (name of the class) and different number of arguments.
A constructor is called depending upon the number and type of arguments passed.
While creating the object, arguments must be passed to let compiler know, which
constructor needs to be called.
17
www.Jntufastupdates.com
// C++ program to illustrate Constructor overloading
#include <iostream.h>
class construct int main()
{ {
public: // Constructor Overloading
float area; // with two different constructors
// of class name
construct() // Constructor with no parameters
{ construct obj1;
area = 0;
construct obj2( 10, 20);
}
obj1.disp();
obj2.disp();
construct(int a, int b) // Constructor with two return 1;
parameters }
{ Output :
area = a * b; 0
} 200
void disp()
{
cout<< area<< endl;
}
};
Destructors
Destructors are the functions that are complimentary to constructors. These are used to
de- initialize objects when they are destroyed. The destructor is called automatically by
the compiler when the object goes out of scope, or when the memory space used by it is
de allocated with the help of delete operator.
The syntax for destructor is same as that for the constructor, the class name is used for
the name of destructor; with a tilde ~ sign as prefix to it.
class A
{
public:
~A();
};
18
www.Jntufastupdates.com
class A int main()
{ {
Public: Aobj1; // ConstructorCalled
A() int x=1 ;
{ if(x)
cout << "Constructor called"; {
} A obj2; // Constructor Called
~A() } // Destructor Called for obj2
{
cout<<”\n Destructor Called, Object Destroyed “;
}
};
Anonymous Objects
It is possible to declare objects without a name, such objects are known as anonymous
objects. In anonymous objects, without an object declaration, a user can initialize and
destroy the contents of a class i.e., originally an object exists but it is hidden.
The anonymous object can access the data members by using this pointer.
this ptr can store the address of the object with which the member function is called.
Anonymous objects are destroyed automatically after their use is over.
Anonymous types are handy when you create types for “use and throw” purposes.
#include <iostream.h>
class Cents {
int cents;
public:
Cents(int value) {
this-> cents = value; // this pointer refers to the address of the object
}
int getCents() const {
return this-> cents;
}
~Cents() {
cout << "Destructor is called" << endl;
}
};
19
www.Jntufastupdates.com
Cents add(const Cents &c1, const Cents &c2) {
return Cents(c1.getCents() + c2.getCents()); // return anonymous Cents value
}
int main()
{
cout << "I have " << add(Cents(6), Cents(8)).getCents() << " cents." << endl;
// print anonymous Cents value
}
add() function is called with two anonymous objects and which will return
another anonymous object contains the addition of two object data members.
It is initialized to zero when first object is created. Only one copy is created for entire
class. It is visible within the class but its life time is the entire program. Type and scope
of each static member variable must be defined outside the class definition. They are
stored separately rather than as a part of the object.
20
www.Jntufastupdates.com
cout<<"Count: "<<count<<endl; getch();
} }
};
int item::count; // This is mandatory for
Static data members of a class, because
we know that static members are not
stored with class data members.
21
www.Jntufastupdates.com
Friend Functions
A friend function of a class is defined outside that class' scope but it has the right to
access all private and protected members of the class. Even though the prototypes for
friend functions appear in the class definition, friends are not member functions.
which case the entire class and all of its members are friends. To declare a function as a
friend of a class, precede the function prototype in the class definition with keyword
friend as follows:
class Box
{
double width;
public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};
To declare all member functions of class ClassTwo as friends of class ClassOne, place a
following declaration in the definition of class ClassOne:
class ClassOne{
.........
friend class ClassTwo;
};
22
www.Jntufastupdates.com
//Program to add two complex numbers using friend function
NESTED CLASSES
A nested class is a class which is declared in another enclosing class. A nested class is a
member and as such has the same access rights as any other member. The members of
an enclosing class have no special access to members of a nested class; the usual access
rules shall be obeyed.
Nested class is a class defined inside a class, that can be used within the scope of the
class in which it is defined. In C++ nested classes are not given importance because of
the strong and flexible usage of inheritance. Its objects are accessed using
"Nest::Display".
#include <iostream.h>
class Nest
{
public:
class Display
{
private:
int s;
23
www.Jntufastupdates.com
public:
void show( )
{
cout << "\nSum of a and b is:: " << s;
}
};
};
void main()
{
Nest::Display x;
x.sum(12, 10);
x.show();
}
Output
Important Questions
2. Define inline function. Write a C++ program for finding the area of a triangle
using inline functions.
Ans : Refer topic Inline Functions (Page no : 7 & 8)
4. Write C++ Program that demonstrates the usage of static data member and static
member function.
Ans : Refer topic Static Members of a class (Page no : 20 & 21)
5. Write C++ program to find the area of a circle, rectangle and triangle using
function overloading.
24
www.Jntufastupdates.com
Ans : Refer Example program (Page no : 13)
8. Write C++ program to add two complex numbers using friend functions.
Ans : Refer Example program (Page no : 23)
Assignment Questions:
1. What is function overloading? Explain function overloading with an example
Program?
2. Explain about static members of a class with an example program ?
3. What is Constructor? What are the different types of constructors ? Explain about
them with examples?
4. Define inline function. Explain about inline functions with an example program ?
5. What is friend function? Explain about friend function with an example program?
25
www.Jntufastupdates.com