Unit III Notes
Unit III Notes
Unit III Notes
public:
Variable declarations;
Function declarations;
};
the class declaration is similar to structure declaration
the keyword class specifies that it follows an abstract data of type class name.the body of the class is
enclosed within braces and terminated by a semicolon(;)
• The members that have been declared as private can be accessed onlyfrom with in the class.
• public members can be accessed from outside the class also.
• 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
member functions.
• Only the member functions can have access to the private data members and private functions.
• However, the public members can be accessed from the outside the class.
• The binding of data and functions together into a single class type variable is referred to as
encapsulation.
Therefore, any member that is declared before any other access specifier has private access automatically.
For example:
class Rectangle
{
int width, height;
public:
void set_values (int,int);
int area (void);
} rect;
Example:
class student
private :
int roll;
char name[30];
public:
void get_data()
cin>>roll>>name;
void put_data()
cout<<”Roll number:”<<roll<<endl;
cout<<”Name :”<<name<<endl;
};
Declaring Object
• Instance of a class is called
object.
• A class is template for an object
and an object is instance of a
class
Syntax:
class_name object_name;
Ex:
student s;
• Once a class has been declared we can create variables of that type by using the class name.
• In C++, the class variables are known as objects.
class item
-----------
-----------
-----------
};
Example:
item x;
• Access Specifiers
– public
• may be accessible from anywhere within a program or
• members are accessible from outside the class
– private
• may be accessed only by the member functions, and friends of
this class
• members cannot be accessed (or viewed) from outside the
class
– protected
• members cannot be accessed from outside the class,
however, they can be accessed in inherited classes.
• acts as public for derived classes
• behaves as private for the rest of the program
Public keyword
Example
class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};
int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
return 0;
}
If you try to access a private member, an error occurs:
error: y is private
• By default, all members of a class
are private if you don't specify an
access specifier:
Example
class MyClass {
int x; // Private attribute
int y; // Private attribute
};
# include <iostream.h>
// class definition
class Circle
{
public:
double radius;
double compute_area()
{
return 3.14*radius*radius;
}
};
// main function
int main()
{
Circle obj;
Defining member
functions
(a) Private or public section
(b) Inside or outside the class
(i)Member function inside the class
#include<iostream.h>
using namespace std;
class Circle
{
// private data member
private:
double radius;
};
// main function
int main()
{
// creating object of the class
Circle obj;
#include <iostream.h>
#include<conio.h>
class Cube
{
public:
int side;
int getVolume();
};
// member function defined outside class definition
int Cube :: getVolume()
{
return side*side*side;
}
int main()
{
Cube C1;
clrscr();
C1.side = 4; // setting side value
cout<< "Volume of cube C1 = "<< C1.getVolume();
getch();
}
Exercise
(a)Write a program to add two numbers by using the concept member
function outside the class
(b) Write a program to find largest of two numbers by using the
concept member function outside the class
Write a program to find largest of two numbers by using the concept member
function outside the class
#include <iostream.h>
#include<conio.h>
class set
{
int m,n;
public:
void input(void);
void display(void);
int largest(void);
};
// member function defined outside class definition
int set :: input()
{
cout<< "enter values of m,n \n"<<;
cin>>m>>n;
}
int set::largest(void)
{
if(m>n)
return(m);
else
return(n);
}
void set::display(void)
{
cout<<"largest value="<<largest()<<"\n";
}
int main()
{
set A;
clrscr();
A.input()
A.display();
getch();
}
(iii)Member function in Public section
# include <iostream.h>
// class definition
class Circle
{
public:
double radius;
double compute_area()
{
return 3.14*radius*radius;
}
};
// main function
int main()
{
Circle obj;
// accessing public datamember outside class
obj.radius = 5.5;
Output:
Radius is: 5.5
Area is: 94.985
// 1. ACCESS PUBLIC MEMBERS USING OBJECTS
#include<iostream.h>
#include<conio.h>
class item
{
public :
int itemcode;
float price;
int quantity;
};
void main()
{
item one;
clrscr();
one.itemcode=1001;
one.price=80.50;
one.quantity=2;
cout<<"\n\t\t ITEM DETAILS";
cout<<"\n\t Item code :"<<one.itemcode;
cout<<"\n\t Item price :"<<one.price;
cout<<"\n\t Item quantity:"<<one.quantity;
getch();
}
(IV)Member function in
private section
#include <iostream.h>
#include<conio.h>
class ITEM
{
int numberr;
float cost
void values()
{
number=123;
cost=53.5;
}
public:
void show()
{
values();
cout<<"\n\t Item code :"<<number;
cout<<"\n\t Item price :"<<cost;
}
};
int main()
{
ITEM A;
clrscr();
A.show();
getch();
}
Data Hiding or Encapsulation
• Data Hiding is also known as
encapsulation
• Process of forming objects and
encapsulated object is called as an
abstract data type
• Data Hiding is nothing but making data
variable of the class private.
• Private data cannot be accessed Directly
by the object
• The objects using public member
functions of the same class can access
the Private data of the class
• Keywords private and protected are used
for hiding the data
// example program to calculate simple interest
//hide the sata elements of the class using private keyword
#include<iostream.h>
#include<conio.h>
class interest
{
private:
float pamount,rate, period;
float interest,totalAmount;
public:
void input()
{
cout<<"Enter principal amount:";
cin>>pamount;
cout<<"\nEnter Rate of Interest:";
cin>>rate;
cout<<"\nNumber of Years:";
cin>>period;
interest=(pamount*period*rate)/100;
totalAmount=interest+pamount;
}
void show()
{
cout<<"\nOUTPUT"<<"\n~~~~~~~~";
cout<<"\nPrincipal Amount:"<<pamount;
cout<<"\nInterest :"<<interest;
cout<<"\nTotal Amount :"<<totalAmount;
}
};
void main()
{
clrscr();
interest r;
r.input();
r.show();
getch();
};
Classes, objects and
memory
• Objects are identifiers declared for class
type
• Object is a composition of one or more
variables declared inside the class
• Each object has its own copy of public
and Private data members
• An object can have access to its own
copy of data members and have no
access to the data members of other
objects
• Declaration of a class does not allocate
memory
• When an object is declared, memory is
reserved for data members only and not
for Member functions
Note:
• Member function are created and memory
is allocated to them only once when a
class declared.
• All objects of a class access the same
memory location where member functions
are stored. Hence, separate copies of
member functions are not present in every
object like member variables
Classes, objects and
memory- EXAMPLE
//program to decalre objects and display their contents
#include <iostream.h>
#include<conio.h>
class month
{
public:
char *name;
int days;
};
void main()
{
month M1,M2;;
clrscr();
M1.name="January:"; // object declaration
M1.days=31;
M2.name="April";
M2.days=30;
cout<< "OBJECT M1: \n ADDRESS ";
cout<<(unsigned)&M1.name;
cout<<"\nMonth M1 Days Address:"<<(unsigned)&M1.days;
cout<< "\nOBJECT M2: \n ADDRESS ";
cout<<(unsigned)&M2.name;
cout<<"\nMonth M1 Days Address:"<<(unsigned)&M2.days;
getch();
}
Note:
• The sizeof() operator displays
the size of objects.
• The size of any object is equal
to sum of sizes of all the data
members of the class.
• Member functions are not
considered in the size of object.
• All the objects of a class use
the same member functions.
• Only one copy of Member
function is created and stored
in the memory whereas each
object has its own set of data
members.
Static member
variables and functions
C++ introduces two more uses for the static keyword
when applied to classes:
(i) static member variables, and
(ii) static member functions.
(i)Static member variables
• Data member of a class can be qualified
us static. the properties of a static
variable are,
A static variable is initialized to 0 when the
first object of its class is created. No other
initialization is permitted.
only one copy of the member is
created for the entire class and is
shared by all the objects of the
class, no matter how many objects
are created.
It is visible only within the class,
but its lifetime is the entire program.
• Static Keyword is used to preserve value
of a variable.
• static function or are data element is only
recognized inside the scope of the present
class.
Syntax:
static<variable definition>;
Example:
static int c;
The class and scope of the static
member variable is defined outside the
class declaration is
class_name :: static_data_member;
Ex. int sumnum::c=0;
//program to declare and display value of static
data member
# include<iostream.h>
# include <conio.h>
class number
{
staic int c;
public:
void count()
{
++c;
cout<<"\n c="<<c;
}
};
int number::c=0;
int main()
{
int number a,b,c;
clrscr();
a.count();
b.count();
c.count();
return 0;
}
Output
c=1
c=2
c=3
Example (static
member)
#include <iostream>
using namespace std;
class Demo
{
private:
static int X;
public:
static void fun()
{
cout <<"Value of X: " << X << endl;
}
};
//defining
int Demo :: X =10;
int main()
{
Demo X;
X.fun();
return 0;
}
Output
Value of X: 10
Showing difference between static and non-static
member variables
// 4. STATIC AND NONSTATIC MEMBER VARIABLES
#include<iostream.h>
#include<conio.h>
class number
{
static int count;
int k;
public:
void zero()
{
k=0;
}
void add()
{
++count;
++k;
cout<<"\t\n\n Value of count ="<<count
<<"\t\n Address of count ="<<(unsigned)&count;
class Example{
static int Number;
int n;
public:
void set_n()
{
n = ++Number;
}
void show_n()
{
cout<<"value of n = "<<n<<endl;
}
};
int main()
{
Example example1, example2;
example1.set_n();
example2.set_n();
example1.show_n();
example2.show_n();
Example::show_Number();
return 0;
}
• static private member function can be
declared in private section.
• The private function must be invoked using
static public function
• Static public member variable can be
initialised in function main like other
variables.
• static member variable using class name and
scope access operator can be accessed.
• scope access operator is also used when
variables of same name are declared in global
and local scope
• example program to declare static public
member variable
• global and local variable with same name
static object
• the object is composition of one or more member
variables. constructor is used to initialise variables of the
object to decide values
• the keyword static can be used to initialise all class data
member variables to zero
• when declaring object as static can initialise the objects
associated members to zero
Array of Objects in
c++
• The array of type class
contains the objects of the
class as its individual elements.
Thus, an array of a class type
is also known as an array of
objects. An array of objects is
declared in the same way as
an array of any built-in data
type.
#include <iostream.h>
#include <string.h>
class Student
{
string name;
int marks;
public:
void getName()
{
getline( cin, name );
}
void getMarks()
{
cin >> marks;
}
void displayInfo()
{
cout << "Name : " << name << endl;
cout << "Marks : " << marks << endl;
}
};
int main()
{
Student st[5];
for( int i=0; i<5; i++ )
{
cout << "Student " << i + 1 << endl;
cout << "Enter name" << endl;
st[i].getName();
cout << "Enter marks" << endl;
st[i].getMarks();
}
for( int i=0; i<5; i++ )
{
cout << "Student " << i + 1 << endl;
st[i].displayInfo();
}
return 0;
}
Student st[5]; - We created an array of 5 objects of the
Student class where each object represents a student having
a name and marks.
The first for loop is for taking the input of name and marks
of the students. getName() and getMarks() are the
functions to take the input of name and marks respectively.
The second for loop is to print the name and marks of all the
5 students. For that, we called the displayInfo() function for
each student.
//5. ARRAY OF OBJECTS
#include<iostream.h>
#include<conio.h>
class student
{
char name[20];
int roll;
int mark1,mark2;
public:
void input(void);
void display(void);
};
void student::input()
{
cout<<"\n Enter student name:";
cin>>name;
cout<<"\n Enter roll number:";
cin>>roll;
cout<<"\n Enter mark1:";
cin>>mark1;
cout<<"\n Enter mark2:";
cin>>mark2;
}
void student::display()
{
cout<<name<<"\t"<<roll<<"\t\t "<<mark1<<"\t"<<mark2<<endl;
}
void main()
{
clrscr();
student s1[3];
cout<<"\n Enter student details";
for(int i=0;i<3;i++)
s1[i].input();
cout<<"\n\n\t STUDENT DETAILS";
cout<<"\n\t ~~~~~~~~~~~~~~~";
cout<<"\n NAME\tROLL NUMBER \t MARK1\tMARK2\t\n";
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
for(i=0;i<3;i++)
s1[i].display();
getch();
}
Passing and Returning Objects in C++
#include <iostream.h>
class Example {
public:
int a;
// Driver Code
int main()
{
// Create objects
Example E1, E2;
return 0;
}
output:
Initial Values
Value of object 1: 50
& object 2: 100
New values
Value of object 1: 50
& object 2: 150
(ii) Returning Object as argument
syntax
object = return object_name;
When the object E3 calls the add function it passes the other
two objects namely E1 & E2 as arguments. Inside the function,
another object is declared which calculates the sum of all the
three variables and returns it to E3.
This code and the above code is almost the same, the only
difference is that this time the add function returns an object
whose value is stored in another object of the same class
‘Example’ E3. Here the value of E1 is displayed by object1, the
value of E2 by object2 and value of E3 by object3.
// C++ program to show passing of objects to a function
#include <iostream.h>
class Example {
public:
int a;
return 0;
}
Output:
Initial Values
Value of object 1: 50,
object 2: 100,
object 3: 0
New values
Value of object 1: 50,
object 2: 100,
object 3: 200
#include<iostream.h>
#include<conio.h>
class account
{
private:
char name[20];
int accno;
float bal;
public:
void read()
{
cout<<" Enter account holder name:";
cin>>name;
cout<<"\n Enter accout number :";
cin>>accno;
cout<<"\n Enter balance :";
cin>>bal;
}
friend void showbal(account);
};
void showbal(account ac)
{
cout<<"\n Balance of Account no:";
cout<<ac.accno<<" is Rs."<<ac.bal;
}
void main()
{
clrscr();
account obj;
cout<<"\tFRIEND FUNCTION\n";
cout<<"\t~~~~~~~~~~~~~~~\n";
obj.read();
showbal(obj);
getch();
}
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 −
Live Demo
#include <iostream>
class Box {
double width;
public:
friend void printWidth( Box box );
void setWidth( double wid );
};
return 0;
}
C++ Recursion
• When function is called within the same function, it is known as recursion in C++. The function which calls the
same function, is known as recursive function.
• A function that calls itself, and doesn't perform any task after function call, is known as tail recursion. In tail
recursion, we generally call the same function with return statement.
recursionfunction(){
recursionfunction(); //calling self function
}
#include<iostream>
using namespace std;
int main()
{
int factorial(int);
int fact,value;
cout<<"Enter any number: ";
cin>>value;
fact=factorial(value);
cout<<"Factorial of a number is: "<<fact<<endl;
return 0;
}
int factorial(int n)
{
if(n<0)
return(-1); /*Wrong value*/
if(n==0)
return(1); /*Terminating condition*/
else
{
return(n*factorial(n-1));
}
}
Output:
1
2
Here is the elements of Second matrix :
3 4
The multiplication of two matrix is :
3 4
6 8
Click me to see the solution
#include <iostream>
using namespace std;
class printData {
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}
void print(double f) {
cout << "Printing float: " << f << endl;
}
void print(char* c) {
cout << "Printing character: " << c << endl;
}
};
int main(void) {
printData pd;
return 0;
}
Printing int: 5
Printing float: 500.263
Printing character: Hello C++
What is constructor?
A constructor is a member function of a class which initializes objects of a class. In C++, Constructor is automatically
called when object(instance of class) create. It is special member function of the class.
How constructors are different from a normal member function?
A constructor is different from normal functions in following ways:
Constructor has same name as the class itself
Constructors don’t have return type
A constructor is automatically called when an object is created.
If we do not specify a constructor, C++ compiler generates a default constructor for us (expects no parameters and
has an empty body).
Types of Constructors in C++
Constructors are of three types:
Default Constructor
Parametrized Constructor
Copy Constructor
• Default Constructors
• Default constructor is the constructor which doesn't take any argument. It has no parameter.
class Cube
{
public:
int side;
Cube()
{
side = 10;
}
};
int main()
{
Cube c;
cout << c.side;
}
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 integer
{
int m,n; public: integer( );
………..
………..
};
integer :: integer( )
{
m=0; n=0;
}
int main()
{ integer obj1;
class demo
public:
demo()
};
void main()
}
clrscr( );
demo d;
getch( )
OUTPUT :
The constructors are always declared in the public section. If declared in the private
section then objects are can only be created inside the member functions but serve no
purpose.
2. They are invoked automatically when objects of the class are created. The declaration
demo d; creates an object d which automatically calls the constructor of the class and
3. They do not have any return type not even void so they cannot return any value.
4. Constructors cannot be inherited, but they can be called from the constructors of derived
class.
6. The constructor with no argument is known as default constructor of the class. The
7. Constructors which take arguments like a function takes are known as parameterized
constructor.
8. There is no limit of the number of constructors declared in a class but they all must
12. Constructor make implicit calls to operators new and delete in case memory allocation
#include <iostream.h>
Class demo
{
public :
demo( ); // declaration
};
void main( )
demo d;
In all
Constructors are of 3 types:
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
1. Default Constructor: A constructor that accepts no parameters is called the default constructor.
#include<iostream.h>
#include<conio.h>
class item
{
int m,n;
public:
item()
{
m=10;
n=20;
}
void put();
};
void item::put()
{
cout<<m<<n;
}
void main()
{
item t;
t.put();
getch();
}
2. Parameterized Constructors:-The constructors that take parameters are called
parameterized constructors.
#include<iostream.h>
class item
{
int m,n;
public:
item(int x, int y)
{
m=x;
n=y;
}
};
When a constructor has been parameterized, the object declaration statement such as
item t; may not work. We must pass the initial values as arguments to the constructor function
when an object is declared. This can be done in 2 ways: item t=item(10,20); //explicit call
Constructor are similar to functions but they have the name as class name so similar to functions
which takes argument we can have constructor which can take arguments. The constructor
which
takes parameters is known as parameterized constructor. Again depending upon type of
arguments
and number of arguments they may be overloaded. An example of this is given below :
/*PROG 7.2 DEMO OF PARAMETERIZED CONSTRUCTOR WITH INTEGER DATA*/
#include <iostream.h>
#include <conio.h>
class demo
{
int a,b;
public :
demo( )
{
a=b=0;
cout<<“Zero argument constructor called\n”;
show( );
}
demo(int x, int y)
{
282 Object-Oriented Programming C++ Simplified
a=x;
b=y;
cout<<“Two argument constructor called\n”;
show( );
}
demo(int x)
{
a=b=x;
cout<<“One argument constructor called\n”;
show( );
}
void show( )
{
cout<<“a=”<<a<<“\tb=”<<b<<endl;
}
};
void main( )
{
clrscr( );
demo d1;
demo d2(10,20);
demo d3(30);
getch( );
}
OUTPUT :
Zero argument constructors called
a=0 b=0
Two argument constructor called
a=10 b=20
One argument constructor called
a=30 b=30
/*PROG 7.4 FACTORIAL OF A NUMBER, FACTORIAL OF 6 IS 6*5*4*3*2*1=720*/
#include <iostream.h>
#include <conio.h>
class fact
{
int fa;
int num;
public :
fact( )
{
fa = 1;
cout<<“Enter the number \n”;
cin>>num;
}
int find_fac( )
{
int i;
for(i=1;i<=num;i++)
fa=fa*i;
return fa;
}
void show( )
{
cout<<“The factorial of”<<num<<“is”<<find_fac( )<<endl;
}
};
void main( )
{
clrscr( );
fact obj;
obj.show( );
getch( );
}
OUTPUT :
Enter the number
6
The factorial of6is720
}
complex sum(complex c )
{
else
}
};
{
img=-img;
cout<<real<<"-i"<<img<<endl;
}
void main()
{
complex c1(1,2); complex c2(2,2); compex c3;
c3=c1.sum(c3); c3.show();
}
DESTRUCTOR
A destructor is a member function of the class whose name
is same as the name of the class
but the preceded with tilde sign (~). The purpose of
destructor is to destroy the object when
it is no longer needed or goes out of scope. As a very small
example of destructor see the
program given below :
/*PROG 7.25 DEMO OF DESTRUCTOR VER 1*/
#include <iostream.h>
#include <conio.h>
class demo
{
public :
demo( )
{
cout<<“Constructor called\n”;
}
~demo( )
{
cout<<“Destructor called”<<endl;
}
};
Working with Constructor and Destructor 329
void main( )
{
clrscr( );
demo d;
getch( );
}
OUTPUT :
Constructor called
Destructor called
EXPLANATION : When demo d; executes it calls the
default constructor of the class and
results in printing Constructor called. The scope of object
d is the area/place where it is
available and in the above program the scope is the whole
main function. Being the only
statement demo d; in the function main, as soon as
compiler finds ending brace of main i.e.,}
it calls destructor of the class to destroy the object d and
prints Destructor called. The code
is given as :
~demo ( )
{
cout<<”Destructor called “<<endl;
}
is a destructor of the class demo.
Features of Destructor
1. The name is same as of class but proceeded with a ~
sign.
2. Destructor is automatically called as soon as an object
goes out of scope.
3. Destructor is used to destroy the objects.
4. Once a destructor is called for a object, the object will
no longer be available for the
future reference.
5. Destructor can be used for housekeeping work such as
closing the file, de-allocating
the dynamically allocated memory etc. Closing a file in
destructor is a good idea as
user might forget to close the file associated with object.
But as the object goes out of
scope destructor will be called and all code written in
destructor executes which will
always result in closing the file and no data loss may be
there. When new is used for
allocation of memory in the constructor we must always
use delete in the destructor
to be allocate the memory.
6. Similar to constructor there is no return type for
destructor and that’s why they cannot
return any value.
7. There is no explicit or implicit category for a destructor.
They are always called
implicitly by the compiler.
8. Destructor can never take any arguments.
330 Object-Oriented Programming C++ Simplified
9. Destructor can be virtual
//constructor Marks() {
cout << "Inside Constructor"<<endl;
cout << "C++ Object created"<<endl;
}
//Destructor
~Marks() {
cout << "Inside Destructor"<<endl;
cout << "C++ Object destructed"<<endl;
}
};
int main( )
{
Marks m1; Marks m2; return 0;
}
Output:
Inside Constructor
C++ Object created
Inside Constructor
C++ Object created
Inside Destructor
C++ Object destructed
Inside Destructor
C++ Object destructed
Without object we can initialize and destroy the content of the class.
All these operations are carried out without object or we can also
assume that operations are carried out using an anonymous object.
1 #include <iostream>
2
3 using namespace std;
4
5 class A {
6 public: A() // constructor
7 {
8 cout << "Constructor executed" << endl;
9 }~A() // Destructor
10 {
11 cout << "Destructor executed" << endl;
12 }
13 };
14 int main() {
15 A(); // calling constructor
16 A(); // calling constructor
17 }
Output
1 Constructor executed
2 Destructor executed
3 Constructor executed
4 Destructor executed
Note: In the above program, we have created class “A” which
contains constructor and destructor.
In the main() function, no object is created.