Unit 2

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 21

Unit 2

Class and Object

What is a class? Give its example.


Class is a user defined data type that combines data and functions together. It is a collection of
objects of similar type.

Example:
class Student
{
int rollno;
char name[10];
public: void getdata( );
void putdata( );
};

Define class and object.

Class:
Class is a user defined data type that combines data and functions
together. It is a collection of objects of similar type.

Object:
It is a basic run time entity that represents a person, place or any item
that the program has to handle.

Program:-
1) Write a C++ program to declare a class ‘circle’ with data
members as radius and area. Declare a function getdata to accept
radius and putdata to calculate and display area of circle.
#include<iostream.h>
#include<conio.h>
class circle
{
float radius,area;
public:
void getdata()
{
cout<<"Enter radius:";
cin>>radius;
}
void putdata()
{
Unit 2

area=3.14*radius*radius;
cout<<"Area of circle="<<area;

}
};
void main()
{
circle c;
clrscr();
c.getdata();
c.putdata();
getch();
}

Example 2:-

2) Write a C++ program to create a class STUDENT


The data members of STUDENT class.
Roll_No
Name
Marks

#include<iostream.h>
#include<conio.h>
class STUDENT
{
int Roll_No;
char Name[20];
float Marks;
public:
void Accept();
void Display();
};
void STUDENT::Accept()

{
cout<<"\nEnter data of student:";
cout<<"\nRoll number:";
cin>>Roll_No;
cout<<"\nName:";
cin>>Name;
cout<<"\nMarks:";
cin>>Marks;
}
void STUDENT::Display()
{
cout<<"\nStudents data is:";
Unit 2

cout<<"\nRoll number:"<<Roll_No;
cout<<"\nName:"<<Name;
cout<<"\nMarks:"<<Marks;
}
void main()
{
STUDENT S[5];
int i;
clrscr();
for(i=0;i<5;i++)
{
S[i].Accept();
}
for(i=0;i<5;i++)
{
S[i].Display();
}
getch();
}

Static data member:-


properties of static member function.

i) A static member function can have access to only other static data members and functions declared
in the same class.
ii) A static member function can be called using the class name with a scope resolution operator
instead of object name as follows: class_name::function_name

Use of static data member:


1. Static data member is used to maintain values common to the entire
class.
2. It is initialized to zero when the first object of its class is created.
3. Only one copy of that member is created for the entire class and is
shared by all the objects of that class

Example:

#include<iostream.h>
#include<conio.h>
class test
{

static int count;


Unit 2

int obj_no;
public:
void getdata()
{
obj_no=++count;
cout<<"\n Object number="<<obj_no;
}
static void showcount()
{
cout<<"\n total number of objects="<<count;
}
};
int test::count;
void main()
{
test t1,t2;
clrscr();
t1.getdata();
t2.getdata();
test::showcount();
test t3;
t3.getdata();
test::showcount();
getch();
}
Unit 2

Describe memory allocation for objects.

The memory space for object is allocated when they are declared and not when the class is specified.
The member functions are created and placed in memory space only once when they are defined as a
part of a class definition. Since all the objects belonging to that class use the same member functions,
no separate space is allocated for member functions. When the objects are created only space for
member variable is allocated separately for each object. Separate memory locations for the objects
are essential because the member variables will hold different data values for different objects.
Unit 2

Destructor:-

A destructor is a special member function whose task is to destroy the objects that have been
created by constructor.
It does not construct the values for the data members of the class.
It is invoked implicitly by the compiler upon exit of a program/block/function
Destructors are not classified in any types
A class can have at the most one constructor
Destructor never accepts any parameter.

Syntax:
destructor name is preceded
with tilde.
~classname()
{….
….
}
Example:
~ABC()
{
….
}
characteristics of destructor:

1. It is used to destroy objects created by a constructor.


2. Name of destructor and name of the class is same.
3. Its name is preceded with tilde (~) symbol.
4. It never takes any argument.
5. It does not return any value.
6. It is invoked implicitly by the compiler upon exit from the
program (or block or function) i.e when scope of object is over.

Rules for writing destructor function are:

1) A destructor is a special member function which should destroy the objects that have been created
by constructor.
2) Name of destructor and name of the class should be same.
3) Destructor name should be preceded with tilde (~) symbol.
4) Destructor should not accept any parameters.
5) Destructor should not return any value.
6) Destructor should not be classified in any types.
7) A class can have at most one destructor.
Unit 2

Example:-

#include<iostream.h>

class Demo {

private:

int num1, num2;

public:

Demo(int n1, int n2) {

cout<<"Inside Constructor"<<endl;

num1 = n1;

num2 = n2;

void display() {

cout<<"num1 = "<< num1 <<endl;

cout<<"num2 = "<< num2 <<endl;

~Demo() {

cout<<"Inside Destructor";

};

int main() {

Demo obj1(10, 20);

obj1.display();

return 0;

Output
Unit 2

Inside Constructor
num1 = 10
num2 = 20
Inside Destructor
Unit 2

Constructor:-
A constructor is a special member function whose task is to initialize the objects of its class.
It constructs the values of data members of the class
It is invoked automatically when the objects are created.
A class can have more than one constructor
Constructor accepts parameters. Also it can have default value for its parameter.
Syntax:
classname()
{…

}
Example:
ABC()
{

}

Types of Constructor:-
Default constructor
Parameterized constructor
Copy constructor
Overloaded constructor
Unit 2

Default Constructor:-

A default constructor is a constructor that either has no parameters, or if it has parameters, all
the parameters have default values. If no user-defined constructor exists for a class A and one
is needed, the compiler implicitly declares a default parameterless constructor A::A()

Example:-

#include <iostream.h>

class DemoDC

private:

int num1, num2 ;

public:

DemoDC() {

num1 = 10;

num2 = 20;

void display() {

cout<<"num1 = "<< num1 <<endl;

cout<<"num2 = "<< num2 <<endl;

};

int main()

DemoDC obj;

obj.display();
Unit 2

return 0;

Parameterized constructor :-
A constructor that accepts parameters is called as parameterized constructor. In some applications, it
may be necessary to initialize the various data members of different objects with different values
when they are created. Parameterized constructor is used to achieve this by passing arguments to the
constructor function when the objects are created

Example:

class ABC
{
int m;
public: ABC(int x)
{ m=x;
}
void put()
{
cout<<m;
}
};
void main()
{
ABC obj(10);
obj.put();
}

In the above example, constructor ABC (int x) is a parameterized constructor function that accepts
one parameter. When „obj‟ object is created for class ABC, parameterized constructor will invoke
and data member m will be initialized with the value 10 which is passed as an argument. Member
function put ( ) displays the value of data member „m‟.

Example:2

Write a C++ program to declare a class addition with data


members as x and y. Initialize values of x and y with constructor.
Calculate addition and display it using function ‘display’.
#include<iostream.h>
Unit 2

#include<conio.h>
class addition
{
int x,y;
public:
addition(int,int);
void display();
};
addition::addition (int x1,int y1)
{
x=x1;
y=y1;
}
void addition::display()
{
cout<<"\nAddition of two numbers is:"<<(x+y);
}
void main()
{
addition a(3,4);
a.display();
getch();
}

Copy Constructor:-

The copy constructor is a constructor which creates an object by initializing it with an


object of the same class, which has been created previously. The copy constructor is
used to −

 Initialize one object from another of the same type.


 Copy an object to pass it as an argument to a function.
 Copy an object to return it from a function.
If a copy constructor is not defined in a class, the compiler itself defines one.If the class
has pointer variables and has some dynamic memory allocations, then it is a must to
have a copy constructor. The most common form of copy constructor is shown here −
classname (const classname &obj)
{
// body of constructor
}
Unit 2

Constructor with default arguments:-

Example:-

Write a C++ program to declare a class student with members as


roll no, name and department. Declare a parameterized
constructor with default value for department as ‘CO’ to
initialize members of object. Initialize and display data for two
students.
(Note: Any other relevant logic should be considered).
#include<iostream.h>
#include<conio.h>
#include<string.h>
class student
{
int roll_no;
char name[20],department[40];
public:
student(int rno,char *n,char *d="CO")
{
roll_no=rno;
strcpy(name,n);
strcpy(department,d);
}
void display()
{
cout<<"\n Roll No:"<<roll_no;
cout<<"\n Name:"<<name;
cout<<"\n Department:"<<department;
}
};
void main()
{
student s1(112," Chitrakshi"),s2(114,"Anjali");
clrscr();
s1.display();
s2.display();
getch();
}
Unit 2

Friend function:

The private members of a class cannot be accessed from outside the class but in some situations two
classes may need access of each other‟s private data. So a common function can be declared which
can be made friend of more than one class to access the private data of more than one class. The
common function is made friendly with all those classes whose private data need to be shared in that
function. This common function is called as friend function. Friend function is not in the scope of the
class in which it is declared. It is called without any object. The class members are accessed with the
object name and dot membership operator inside the friend function. It accepts objects as arguments.

Example: Program to interchange values of two integer numbers using friend function

#include<iostream.h>
#include<conio.h>
class B;
class A
{
int x;
public:
void accept()
{
cout<<"\n Enter the value for x:"; cin>>x;
}
friend void swap(A,B);
};
class B
{
int y;
public:
void accept()
{
cout<<"\n Enter the value for y:";
cin>>y;
}
friend void swap(A,B);
};
void swap(A a,B b)
{
cout<<"\n Before swapping:";
cout<<"\n Value for x="<<a.x;
cout<<"\n Value for y="<<b.y;
int temp;
Unit 2

temp=a.x;
a.x=b.y;
b.y=temp;
cout<<"\n After swapping:";
cout<<"\n Value for x="<<a.x;
cout<<"\n Value for y="<<b.y;
}
void main()
{
A a;
B b;
clrscr();
a.accept();
b.accept();
swap(a,b);
getch();
}

Example 2:

Write a C++ program to find greatest number among two


numbers from two different classes using friend function.
#include<iostream.h>
#include<conio.h>
class second;
class first
{
int x;
public:
void getx()
{
cout<<"\nEnter the value of x:";
cin>>x;
}
friend void max(first,second);
};
class second
{
int y;
public:
void gety()
{
cout<<"\nEnter the value of y:";
cin>>y;
}
Unit 2

friend void max(first,second);


};
void max(first a,second b)
{
if(a.x>b.y)
{
cout<<"\Greater value is:"<<a.x;
}
else
{
cout<<"\nGreater value is:"<<b.y;
}
}
void main()
{
first a;
second b;
clrscr();
a.getx();
b.gety();
max(a,b);
getch();
}

Example3:-

Write a C++ program to find smallest number from two numbers


using friend function. (Hint: use two classes).
(Note: Any other correct logic shall be considered)
#include<iostream.h>
#include<conio.h>
class class2;
class class1
{
int no1;
public:
void get1()
{
cout<<"Enter number 1:";
cin>>no1;
}
friend void smallest(class1 no1,class2 no2);
};
class class2
{
int no2;
Unit 2

public:
void get2()
{
cout<<"Enter number 2:";
cin>>no2;
}
friend void smallest(class1 no1,class2 no2);
};
void smallest(class1 c1,class2 c2)
{
if(c1.no1<c2.no2)
cout<<"no1 is smallest";
else
cout<<"no2 is smallest";
}
void main()
{
class1 c1;
class2 c2;
clrscr();
c1.get1();
c2.get2();
smallest(c1,c2);
getch();
}

Array of Object:
Unit 2

Example:1

Write a program to declare a class ‘student’ having data members as ‘stud_name’ and
‘roll_no’. Accept and display this data for 5 students.
(Note: Any other correct logic shall be considered)

#include<iostream.h>
#include<conio.h>
class student
{
int roll_no;
char stud_name[20];
public:
void Accept();
void Display();
};
void student::Accept() {
cout<<"\n Enter student‟s name and roll no\n";
cin>>stud_name>>roll_no;
}
void student::Display()
{
cout<<stud_name<<”\t”<<roll_no<<”\n”;
}
void main()
{
student S[5];
int i;
clrscr();
for(i=0;i<5;i++)
{
S[i].Accept();
}
cout<<”Student details \n Student‟s Name \t Roll No\n”;

for(i=0;i<5;i++)
{
S[i].Display();
}
getch();
}
Unit 2

Example 2:-
Write a C++ program to declare a class ‘Account’ with data
members as accno, name and bal. Accept data for eight accounts
and display details of accounts having balance less than 10,000.

#include<iostream.h>
#include<conio.h>
class Account
{
long int accno, bal;
char name[10];
public:
void getdata()
{
cout<<"\nEnter account number, balance and name ";
cin>>accno>>bal>>name;
}
void putdata()
{
if(bal>10000)
{
cout<<"\nThe Account Number is "<<accno;
cout<<"\nThe Balance is "<<bal;
cout<<"\nThe Name is "<<name;
}
}
};
void main()
{
Account a[8];
int i;
clrscr();
for(i=0;i<8;i++)
{
a[i].getdata();
}
for(i=0;i<8;i++)
{

a[i].putdata();
}
getch();
}

Constructor in derived classes:-


Unit 2

Describe with examples, passing parameters to base class


constructor and derived class constructor by creating object of
derived class.

When a class is declared, a constructor can be declared inside the class to initialize data
members. When a base class contains a constructor with one or more arguments then it is
mandatory for the derived class to have a constructor and pass arguments to the base class
constructor. When both the derived and base classes contain constructors, the base constructor is
executed first and then the constructor in the derived class is executed. The constructor of
derived class receives the entire list of values as its arguments and passes them on to the base
constructors in the order in which they are declared in the derived class.

General form to declare derived class constructor:


Derived-constructor (arglist1, arglist (D)):Base1(arglist1)
{
Body of derived class constructor
}

Derived constructor declaration contains two parts separated with colon (:). First part provides
declaration of arguments that are passed to the derived constructor and second part lists the
function calls to the base constructors.

Example:

#include<iostream.h>
#include<conio.h>
class base
{
int x;
public:
base(int a)
{
x=a;
cout<<"Constructor in base x="<<x;
}
};
class derived: public base
{
int y;
public:
derived(int a,int b):base(a)
{
y=b;
cout<<"Constructor in derived.y="<<y;
}
};
void main()
Unit 2

{
clrscr();
derived ob(2,3);
getch();
}
In the above example, base class constructor requires one argument and derived class constructor
requires one argument. Derived class constructor accepts two values and passes one value to
base class constructor.

You might also like