Unit 2C++

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

Object Oriented Programming through C++

UNIT II

Classes and Objects &Constructors and Destructor: 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, Destructors, Anonymous Objects.

CLASSES IN C++

A class is used to pack data members and member function together. The class has a mechanism
to prevent direct access to its members, which is the central idea of object-oriented
programming. The class declaration is also known as formation of new abstract data type. The
abstract data type can be used as basic data type such as int, float, etc.

Syntax:

Class consist of 4 different components


• Class name
• Data member
• member function
• Access specifier
 Data members:
Variables that are define inside the class is known as data members

 member function
Functions that are defined inside the class is known as member function

 Access specifier
It can control data members and member functions
It is categorized into three types
1.private: It can be accessible within the class
2.protected: It can be accessible within the class or within in the subclass
3.public: It can be accessible in any point of the program.

Example:

class Test
{
private:
int data1;
float data2;

public:
void function1()
{
data1 = 2;
}

float function2()
{
data2 = 3.5;
return data2;
}
};

DECLARING OBJECTS
The declaration of objects is same as declaration of variables of basic data types. Defining
objects of class data type is known as class instantiation. Only when objects are created,
memory is allocated to them.
Consider the following examples.

 Int x,y,z; // Declaration of integer variables


 char a,b,c; // Declaration of character variables
 item a,b, *c; // Declaration of object or class type variables

In the example (a), three variables x, y, and z of int types are declared. In the example (b),
three variables a, b, and c of char type are declared. In the same fashion the third example
declares the three objects a, b, and c of class item. The object *c is pointer to class item.

 access to class members: The object can access the public data member and member
functions of a class by using dot (.) and arrow (->) operators. The syntax is as follows:
[Object name][Operator][Member name]
 To access data members of class the statement would be as follows:
a.show();
 where a is an object and show() is a member function. The dot operator is used
because a is a simple object.
 In statement
c->show();
*c is pointer to class item; therefore, the arrow operator is used to access the member.

Program for calculating area of circle - object declaration example


#include<iostream>
using namespace std;

class circle
{
int r,area;
public:
void getdata()
{
cout<<"\n Enter the Radius : ";
cin>>r;
}
void calculate()
{
area = 3.14 * r* r;
cout<<" \n Area of Circle : \n "<<area;
}
};

int main()
{
circle c;
c. getdata();
c.calculate ();
circle *b;
b->getdata();
b->calculate();
}
OUTPUT:
Enter the Radius : 4 Area of Circle :50
Enter the Radius : 8 Area of Cir
cle : 200

ACCESS SPECIFIER AND THEIR SCOPE

Public:
 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.
The public members of a class can be accessed from anywhere in the program using the direct
member access operator (.) with the object of that class.
#include <iostream>
using namespace std;
class circle
{
public:
double area,r;
public:
void calculate()
{
area=3.14*r*r;
cout<<"area of circle"<<area;
}
};

int main()
{
circle c;
c.r=5.5; // accessing public data member outside class
c.calculate();
}
Output:
Area of circle 94.985

In the above program the data member radius is public so we are allowed to access it outside the
class.

Private:
 The class members declared as private can be accessed only by the functions inside the
class. They are not allowed to be accessed directly by any object or function outside the
class.
 Only the member functions or the friend functions are allowed to access the private data
members of a class.

#include <iostream>
using namespace std;
class circle
{
private:
double area,r;
public:
void calculate()
{
area=3.14*r*r; // memberfunction can access private data member i.e r
cout<<"area of circle\n "<<area;
}
};

int main()
{

circle c;

c.r=1.5; // trying to access private data member directly outside the class

c.calculate();

The output of above program will be a compile time error because we are not allowed to access
the private data members of a class directly outside the class.
Output:
main.cpp: In function ‘int main()’:
main.cpp:26:3: error: ‘double circle::r’ is private within this context
c.r=1.5; // trying to access private data member directly outside the class
^main.cpp:14:17: note: declared private here
double area,r;
^

However, we can access the private data members of a class indirectly using the public member
functions of the class. Below program explains how to do this:

#include <iostream>
using namespace std;
class circle
{
private:
double area,r;
public:
void calculate(double r)
{
area=3.14*r*r; // memberfunction can access private data member i.e r
cout<<"area of circle:"<<area;
}
};

int main()
{
circle c;
// trying to access private data member directly outside the class
c.calculate(1.5);
}

Output:
area of circle: 7.065
Protected:
Protected access modifier is similar to that of private access modifiers, the difference is that the
class member declared as Protected are inaccessible outside the class but they can be accessed by
any subclass(derived class) of that class.

#include <iostream>
using namespace std;
// base class
class ParentCircle
{
// protected data members
protected:
double radius;
};
// sub class or derived class
class ChildCalculate : public ParentCircle
{
public:
void area(double r)
{
// Child class is able to access the inherited protected data members of base class i.e radius

radius = r;
double circlearea=3.14*radius*radius;
cout<< "area of circle is" <<circlearea<<endl;
}

};
// main function
int main() {
ChildCalculate obj1;
// member function of the derived class can access the protected data members of the base class
obj1.area(1.5);

OUTPUT:
area of circle is 7.065
DEFINING MEMBER FUNCTIONS
The member function must be declared inside the class. They can be defined as
(a) private or public section (b) inside or outside the class.
Member function Inside the class
 If the member function is small then it should be defined inside the class.
 If the member function is simple if does not consist loops and recursion
Write a program to create a class for a student to get and display the details of the student.
- member function inside the class

#include <iostream>
using namespace std;
class student
{
private:
char name[25];
int rNo;
float perc;
public:
void getdata ()
{
cout<< "Enter name: " ;
cin>> name;
cout<< "Enter roll number: ";
cin>>rNo;
cout<<"student perc:";
cin>>perc;
}
void display()
{
cout<< "Student name\t"<<name;
cout<<"\n Student roll number: \t" <<rNo ;
cout<<"\n Student perc:\t"<< perc;
}
};
int main()
{
student s;
s.getdata();
s.display();
return 0;
}
Output:

Enter name: sandhya


Enter roll number: 70
student perc:88
Student name sandhya
Student roll number: 70
Student perc: 88

Member Function Outside the class


 If the member function is large and having loops then it must be defined outside
the class.
 To define a function outside the following steps are to be followed
Step 1: function declaration can be done inside the class
Step 2: function definition can be done outside the class .function name must be preceded by
classname and its returntypeseparated by scope resolution operator (::)
Syntax:
returntype classname :: functionname(list of parameters)
{
Body;
}
Write a program to find sum of'' N ' numbers. - member function outside the class
#include<iostream>
using namespace std;
class sum
{
int n,i,s;
public:
void getdata()
{
cout<<"enter n value";
cin>>n;
}
void calculate();
};
void sum::calculate()
{
int sum,i;
sum =0;
for (i=1; i<=n; i++)
{
sum = sum + i;
}
cout<<"sum is:"<< sum;
}
int main()
{
sum t;
t.getdata();
t.calculate();
return 0;
}

OUTPUT:

enter n value6
sum is:21

NESTED CLASS:

 When a class defined in another class, it is known as nesting of classes.

 The nested class is also a member variable of the enclosing class and has the same access
rights as the other members.

 However, the member functions of the enclosing class have no special access to the
members of a nested class.

#include<iostream>
using namespace std;
class A {
public:
class B {
private:
int num;
public:
void getdata(int n) {
num = n;
}
void putdata() {
cout<<"The number is "<<num;
}
};
};
int main() {
cout<<"Nested classes in C++"<< endl;
A :: B obj;
obj.getdata(9);
obj.putdata();
return 0;
}

OUTPUT

Nested classes in C++


The number is 9

In the above program, class B is defined inside the class A so it is a nested class. The class B
contains a private variable num and two public functions getdata() and putdata(). The function
getdata() takes the data and the function putdata() displays the data.

In the function main(), an object of the class A and class B is defined. Then the functions
getdata() and putdata() are called using the variable obj.

METHOD OVERLOADING / FUNCTION OVERLOADING:


If any class have multiple functions with same names but different parameters then they are said
to be overloaded. Function overloading allows you to use the same name for different functions,
to perform, either same or different functions in the same class.
Function overloading is usually used to enhance the readability of the program. If you have to
perform one single operation but with different number or types of arguments, then you can
simply overload the function.

Ways to overload a function

1. By changing number of Arguments.


2. By having different types of argument.

Write a program to find addition between two integer numbers and two floating point
numbers.- By changing number of Arguments
#include<iostream>
using namespace std;
class addition
{
public:
int add(int a, int b)
{
return(a+b);
}
double add(double d ,double e)
{
return (d+e);
}
};
int main()
{
addition ob;cout<<"addition between 3 and 5 \t";
cout<<ob.add(3,5);
cout<<"\n addition between 3.5,5.6\t";
cout<<ob.add(3.5, 5.6);
return 0;
}

OUTPUT

addition between 3 and 5 8 addition between 3.5,5.6 9.1

Write C++ program to find the area of a circle , rectangle and triangle using function
overloading. - By having different types of argument

#include<iostream>
using namespace std;
int area(int);
int area(int,int);
float area(float);
float area(float,float);
int main()
{
int s,l,b;
float r,bs,ht;
cout<<"Enter side of a square:";
cin>>s;
cout<<"Enter length and breadth of rectangle:";
cin>>l>>b;
cout<<"Enter radius of circle:";
cin>>r;
cout<<"Enter base and height of triangle:";
cin>>bs>>ht;
cout<<"Area of square is"<<area(s);
cout<<"\nArea of rectangle is "<<area(l,b);
cout<<"\nArea of circle is "<<area(r);
cout<<"\nArea of triangle is "<<area(bs,ht);
}
int area(int s)
{
return(s*s);
}
int area(int l,int b)
{
return(l*b);
}
float area(float r)
{
return(3.14*r*r);
}
float area(float bs,float ht)
{
return((bs*ht)/2);
}

OUTPUT:

Enter side of a square: 3 Enter length and breadth of rectangle:4 5

Enter radius of circle:3 Enter base and height of triangle:2 4


Area of square is9
Area of rectangle is 20 Area of circle is 28.26
Area of triangle is 4

CONSTRUCTOR
Constructors is a special member function used to initialize data member

Constructor is used for:

 To initialize data member of class: In the constructor member function (which will be
declared by the programmer) we can initialize the default vales to the data members and
they can be used further for processing.
 To allocate memory for data member: Constructor can also be used to declare run time
memory (dynamic memory for the data members).

CHARACTERISTICS OF CONSTRUCTOR:
 Constructors have the same name as that of the class they belongs to.
 Constructors must be declared in public section.
 They automatically execute whenever an object is created.
 Constructors will not have any return type even void.
 Constructors will not return any values
 The main function of constructor is to initialize data member
 Constructors can be overloaded
Constructors are classified into 3 types
1. default constructor
2. parameterised constructor
3. copy constructor
Default constructor: A constructor without any arguments is called as default constructor.
Or without passing any arguments to the constructor is known as default constructor

#include<iostream>
using namespace std;
class student
{
private : int sno;
float perc;
public: student()
{
sno=100;
perc=97.56;
}
void display()
{
cout<<"sno="<<sno;cout<<"\n perc="<< perc;
}
};
int main()
{
student S1;
S1.display();
return 0;
}
OUTPUT
sno=100 perc=97.56

Parameterised constructor A constructor with arguments is called as parameterised


constructor. Or Passing parameters to the constructor is known as parameterised constructor

public: student(int s, float p)


{
sno=s;
perc=p;
}
void display()
{
cout<<"sno="<<sno;
cout<<"\n perc="<< perc;
}
}
int main()
{
student S1(101,90.75);
S1.display();
return 0;
}
OUTPUT
sno=101 perc=90.75

Copy constructor
 A copy is a member function which initialize an object using another object of same class

 It is possible to pass reference of object to the constructor such declaration is known as


copy constructor

syntax: classname(classname &object)


{
Body;
}
Syntax for copy constructor declaration in the main program

classname object1(parameter);
classname object2(object1);
or
Classname object2=object

#include<iostream>
using namespace std;
class student
{
private : int sno;
float perc;
public: student(int s, float p)
{
sno=s;
perc=p; int main()
} {
student(studentstudent
&s) s1(101,90.75);
{ student s2(s1);
sno=s.sno; s1.display();
perc=s.perc; s2.display();
} return 0;
void display() }
{
cout<<"\n sno="<<sno;
cout<<"\n perc="<< perc;
}
};
int main()
{
student s1(101,90.75);
student s2(s1);
s1.display();
s2.display();
return 0;
}

OUTPUT

sno=101 perc=90.75
sno=101 perc=90.75

OVERLOADED CONSTRUCTOR or MULTIPLE CONSTRUCTORS

#include<iostream>
using namespace std;
class student
{
private : int sno;
float perc;
public: student(int s, float p)
{
sno=s;
perc=p;
}
student()
{
cout<<"Enter sno:";
cin>>sno;
cout<<"\n Enter perc";
cin>>perc;
}
void display()
{
cout<<"\n sno="<<sno;
cout<<"\n perc="<< perc;
}
};
int main()
{
student s1;
student s2(101,90.75);
s2.display();
return 0;
}
OUTPUT

Enter sno:2 Enter perc56


sno=101 perc=90.75

DESTRUCTOR (~)

Destructor destroys the class object created by the constructors. destructor have the same name
as their class, preceded by tilde symbol.

CHARACTERISTICS:

 Destructor is a special member function like a constructor. Destructors destroy the

 class objects that are created by constructors.

 The destructor have the same name as their class, preceded by a ~. (Tilde symbol)

 it doesn’t accept arguments

 it doesn’t have returns type.

 It is automatically executed when the object goes out of score.

 Destructor releases memory space occupied by the objects.

#include<iostream>
using namespace std;
class student
{
private : int sno;
float perc;
public: student()
{
sno=100;
perc=97.56;
}
void display()
{
cout<<"sno="<<sno;cout<<"\n perc="<< perc;
}
~ student()
{
cout<<"\n object is destroyed";
}
};
int main()
{
student S1;
S1.display();
return 0;
}
OUTPUT:

sno=100
perc=97.56

object is destroyed

ANONYMOUS OBJECTS
 Objects are created with names. It is possible to declare objects without name. Such
objects are known as anonymous objects.
 When constructors and destructors are invoked, the data members of the class are
initialized and destroyed, respectively.
 Thus, without object we can initialize and destroy the contents of the class.
 All these operations are carried out without object or we can also assume that the
operations are carried out using an anonymous object, which exists but is hidden.
 It is not possible to invoke member function without using object but we can invoke the
special member functions constructors and destructors which compulsorily exist in every
class.
 Thus, without the use of constructor and destructor, the theory of anonymous
object cannot be implemented in practice. Consider the following example:
Write a program to create an anonymous object. Initialize and display the contents of
member variables.
#include<conio.h>
#include<iostream>
using namespace std;
class noname
{
private:
int x;
public:
noname (int j)
{
cout<<"\n In constructor";
x=j;
show();
}
noname()
{
cout<<"\n In constructor";
x=15;
show();
}
~noname() { cout<<"\n In destructor"; }
noname *const show()
{
cout<<endl<<"x:"<<x;
return this;
}
};
int main()
{
noname();
noname
(12);
}

OUTPUT:
In constructor x:15
In destructor
In constructor x:12
In destructor

Explanation: In the above program, class noname is declared with one integer data member.
The class also has constructor, destructor, and member function. The member function show() is
used to display the contents on the screen.

In function main(), no object is created. The constructor is called directly. Calling constructor
directly implies creating anonymous objects. In the first call of the constructor, the member
variable is initialized with 15. The constructor invokes the member function show() that displays
the value of x on the screen.

It is not possible to create more than one anonymous object at a time. When constructor
execution work is over destructor destroys the object. Again, the constructor with one argument
is called and integer is passed to it. The member variable is initialized with 12 and it is displayed
by show() function. Finally, the destructor is executed that marks the end of program.

STATIC MEMBER VARIABLE (OR) STATIC DATA MEMBER

Every normal object has a separate copy of data member. It is possible to create common
member variable by using “static” key word

Important points about static variable:


 Only one copy is created for the whole class
 Initial value of static variable is 0;
 Memory for static variable is allocated only once
 Initialization of static variable can be done out side the class
 If one object modifies the data,it can be affected to all the remaing objects of the same
class

Syntax: for declaration of the static variable

static datatype variablename;

Write a program to declare static data members

#include <iostream>
using namespace std;
class sample
{
static int count;
public:
void display()
{
count++;
cout << "count="<< count<<"\n";
}
};
int sample::count=0;
int main()
{
sample x,y,z;
x.display();
y.display();
z.display();
}
Output
count=1 count=2
count=3

Static member function

 When a function is defined a static ,it can access of static data.


 A static member function can be accessed by using classname.

Syntax: to call the member function

classname::functionname( list of parameters);


Write a program to define a static member function

#include <iostream>
using namespace std;
class sample
{
static int count;
public:
static void display()
{
count++;
cout << "count="<< count<<"\n";
}
};
int sample::count=0;
int main()
{
sample::display();
sample::display();
sample::display();
}
Output:

count=1 count=2
count=3

FRIEND FUNCTION:

 If a function is defined as a friend function in C++, then the protected and private data of
a class can be accessed using the function.
 By using the keyword friend compiler knows the given function is a friend function.
 For accessing the data, the declaration of a friend function should be done inside the body
of a class starting with the keyword friend.

Declaration of friend function in C++


class class_name
{
friend data_type function_name(argument/s); // syntax of friend function.
};
In the above declaration, the friend function is preceded by the keyword friend. The function can
be defined anywhere in the program like a normal C++ function. The function definition does
not use either the keyword friend or scope resolution operator.

Characteristics of a Friend function:


o The function is not in the scope of the class to which it has been declared as a friend.
o It cannot be called using the object as it is not in the scope of that class.
o It can be invoked like a normal function without using the object.
o It cannot access the member names directly and has to use an object name and dot
membership operator with the member name.
o It can be declared either in the private or the public part.

#include <iostream>
using namespace std;
class student
{
int sno;
float perc;
public: void read()
{
sno=100;
perc=97.56;
}
friend void display(student);
};
void display(student s1)
{
cout<<"sno="<<s1.sno;
cout<<"\t perc="<<s1.perc;
}
int main()
{
student s2;
s2.read();
display(s2);
return 0;
}

Output:

sno=100 perc=97.56
Write a program to declare friend function to calculate the sum of integers of both the
classes using friend sum function.

#include<iostream>
using namespace std;
class first;
class second
{
int b;
public: void read()
{
cout<<"enter b value";
cin>>b;
}
friend void sum(first,second);
};
class first
{
int a;
public: void read()
{
cout<<"enter a value";
cin>>a;
}
friend void sum(first,second);
};
void sum(first f1,second s1)
{
cout<<"sum="<<f1.a+s1.b;
}
int main()
{
first f;
second s;
f.read();
s.read();
sum(f,s);
return 0;
}

Output:
enter a value 4 enter b value6
sum=10

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy