0% found this document useful (0 votes)
96 views

Object Oriented Programming Through C C2

1. A class is used to bind data and functions together by encapsulating them. It allows data and functions to be hidden from external use if necessary. 2. A class can have private, protected, and public members that control access. Private members can only be accessed within the class, protected within the class and subclasses, and public from anywhere. 3. Constructors are special member functions that initialize objects. They are called automatically when an object is created and have the same name as the class but no return type. Constructors can be default, parameterized, or copy constructors.

Uploaded by

Shailesh Waghole
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
96 views

Object Oriented Programming Through C C2

1. A class is used to bind data and functions together by encapsulating them. It allows data and functions to be hidden from external use if necessary. 2. A class can have private, protected, and public members that control access. Private members can only be accessed within the class, protected within the class and subclasses, and public from anywhere. 3. Constructors are special member functions that initialize objects. They are called automatically when an object is created and have the same name as the class but no return type. Constructors can be default, parameterized, or copy constructors.

Uploaded by

Shailesh Waghole
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Smartworld.asia Specworld.

in

Chapter 2
Class and Object
A class is a way to bind the data and its associated functions together. It allows the data and functions
to be hidden, if necessary, from external use. A class declaration is similar syntactically to a structure.

General form of a class declaration is:

class class_name
{
private:
Variable declaration/data members; Private members can be accessed only from within
Function declaration/ member functions; the class.

protected:
Variable declaration/data members; Protected members can be accessed by own class
Function declaration/ member functions; and its derived classes.

public:
Variable declaration/data members; Public members can be accessed from outside the
Function declaration/ member functions; class also.
};

Points to remember!
 The variables declared inside the class definition are known as data members and the functions
declared inside a class are known as member functions.
 Wrapping of data and function and function into a single unit (i.e. class) is known as data
encapsulation.
 By default the data members and member function of a class are private.
 Private data members can be accessed by the functions that are wrapped inside the class.

General steps to write a C++ program using class and object:

 Header files
 Class definition
 Member function definition
 void main function

Program 2.1 Write a program to find sum of two integers using class and object.

Solution:
#include<iostream.h>

30
1
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in

class Add

{
int x, y, z;
public:
void getdata()
{
cout<<”Enter two numbers”;
cin>>x>>y;
}
void calculate(void);
void display(void);
};

void Add :: calculate()


{
z=x+y;
}

void Add :: display()


{
cout<<z;
}

void main()
{
Add a;
a.getdata();
a.calculate();
a.display();
}

Output:
Enter two numbers 5 6
11

A member function can be defined:

(i) Inside the class definition


(ii) Outside side the class definition using scope resolution operator (::).

31
2
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in

 Here in the above example we are defining the member function getdata() inside the class
definition. And we are defining the member functions calculate() and display(), outside the class
definition using the scope resolution operator.
 Here void Add :: calculate() means the scpoe of member function calculate() is inside the class
Add or we can say the function calculate() belongs to the class Add. :: is the scope resolution
operator which tells the scope of a member function.
 We cannot directly call a function, we can call it using object (through . operator) of the class in
which the function is declared.

How to access member of a class?


To access member of a class dot operator is used. i.e.
object-name.data-member and
object-name.member-function

Application of Scope resolution operator (::)


 It is used to specify scope of a member function.
 It is used to access a global variable.

Object as Function argument


Program 2.2 Write a program to add two time objects (in the form hh:mm).

Solution:
#include<iostream.h>
class time
{
int hours, minutes;

public:
void gettime(int h, int m)
{
hours=h;
minutes=m;
}
void sum(time, time);
void display(void);
};
void time :: sum (time t1, time t2)
{
minutes=t1.minutes+t2.minutes;
hours=minutes/60;

32
3
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in

minutes=minutes%60;
hours=hours+t1.hours+t2.hours;
}
void time :: display()
{
cout<<hours<<” : ”<<minutes<<endl;
}

void main()
{
time T1, T2, T3;
T1.gettime(2,45);
T2.gettime(3,30);
T3.sum(T1, T2);
T1.display();
T2.display();
cout<<"Addition of above two time is ";
T3.display();
}

Output:
2 : 45
3 : 15
Addition of above two time is 6:15

Array of object

Collection of similar types of object is known as array of objects.

Program 2.3 Write a program to input name and age of 5 employees and display them.

Solution:
#include<iostream.h>
class Employee
{
char name[30];
int age;
public:
void getdata(void);
void putdata(void);
};

33
4
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in

void Employee:: getdata(void)


{
cout<<”Enter Name and Age:”;
cin>>name>>age;
}

void Employee:: putdata(void)


{
cout<<name<<”\t”<<age<<endl;
}

void main()
{
Employee e[5];
int i;
for(i=0; i<5; i++)
{
e[i].getdata();
}
for(i=0; i<5; i++)
{
e[i].putdata();
}
}

Output:
Enter Name and Age: Rajib 25
Enter Name and Age: Sunil 27
Enter Name and Age: Ram 23
Enter Name and Age: Bibhuti 26
Enter Name and Age: Ramani 32
Rajib 25
Sunil 27
Ram 23
Bibhuti 26
Ramani 32

Constructor

 A constructor is a special member function whose task is to initialize the object of a class.
 Its name is same as the class name.
 A constructor does not have a return type.

34
5
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in

 A constructor is called or invoked when the object of its associated class is created.
 It is called constructor because it constructs the values of data members of the class.
 A constructor cannot be virtual (shall be discussed later on).
 A constructor can be overloaded.

There three types of constructor:

(i) Default Constructor


(ii) Parameterized Constructor
(iii) Copy constructor

Default Constructor

The constructor which has no arguments is known as default constructor.


Program 2.4 Demonstration of default Constructor.

Solution:
#include<iostream.h>
class Add
{
int x, y, z;

public:
Add(); // Default Constructor
void calculate(void);
void display(void);
};
Add::Add()
{
x=6;
y=5;
}
void Add :: calculate()
{
z=x+y;
}
void Add :: display()
{
cout<<z;
}
void main()
{
Add a;
a.calculate();

35
6
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in

a.display();
}

Output:
11

Note: Here in the above program when the statement Add a; will execute (i.e. object is created), the
default constructor Add () will be called automatically and value of x and y will be set to 6 and 5
respectively.

Parameterized constructor

The constructor which takes some argument is known as parameterized constructor.

Program 2.5 Write a program to initialize two integer variables using parameterized
constructor and add them.

Solution:
#include<iostream.h>
class Add
{
int x, y, z;
public:
Add(int, int);
void calculate(void);
void display(void);
};
Add :: Add(int a, int b)
{
x=a;
y=b;
}
void Add :: calculate()
{
z=x+y;
}
void Add :: display()
{
cout<<z;
}
void main()
{

36
7
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in

Add a(5, 6);


a.calculate();
a.display();
}
Output:
11
Note: Here in the above program when the statement Add a(5, 6); will be executed (i.e. object
creation), the parameterized constructor Add (int, int) will be called automatically and value of x and y
will be set to 5 and 6respectively.
A parameterized constructor can be called:

(i) Implicitly: Add a(5, 6);


(ii) Explicitly :Add a=Add(5, 6);
If the constructor has one argument, then we can also use object-name=value-of-argument; instead of
object-name (value-of-argument); to initialize an object.

What is Dynamic Initialization of an object?


The initialization of an object at the time of execution of program is known as dynamic initialization of
an object. It is achieved by parameterized constructor.

Copy Constructor
The constructor which takes reference to its own class as argument is known as copy constructor.

Program 2.6 Write a program to initialize two integer variables using parameterized
constructor. Copy given integers into a new object and add them.

Solution:
#include<iostream.h>
class Add
{
int x, y, z;
public:
Add()
{
}
Add(int a, int b)
{
x=a;
y=b;

37
8
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in

}
Add(Add &);
void calculate(void);
void display(void);
};

Add :: Add(Add &p)


{
x=p.x;
y=p.y;
cout<<”Value of x and y for new object: ”<<x<<” and ”<<y<<endl;
}
void Add :: calculate()
{
z=x+y;
}
void Add :: display()
{
cout<<z;
}
void main()
{
Add a(5, 6);
Add b(a);
b.calculate();
b.display();
}

Output:
Value of x and y for new object are 5 and 6
11

Note: Here in the above program when the statement Add a(5, 6); will execute (i.e. object creation), the
parameterized constructor Add (int, int) will be called automatically and value of x and y will be set to 5
and 6respectively. Now when the statement Add b(a) ; will execute, the copy constructor Add(Add& )
will be called and the content of object a will be copied into object b.

What is Constructor Overloading?


If a program contains more than one constructor, then constructor is said to be overloaded.

38
9
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in

Destructor

 It is a special member function which is executed automatically when an object is destroyed.


 Its name is same as class name but it should be preceded by the symbol ~.
 It cannot be overloaded as it takes no argument.
 It is used to delete the memory space occupied by an object.
 It has no return type.
 It should be declared in the public section of the class.
Program 2.7 Demonstration of Destructor.

Solution:
#include<iostream.h>
class XYZ
{
int x;
public:
XYZ( );
~XYZ( );
void display(void);
};
XYZ::XYZ( )
{
x=9;
}

XYZ:: ~XYZ( )
{
cout<<”Object is destroyed”<<endl;
}
void XYZ::display()
{
cout<<x;
}
void main()
{
XYZ xyz;
xyz.display();
}

Output:
9
Object is destroyed.

39
10
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in

Inline function

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.
 A function which is expanded in a line when it is called is called inline function.
 It executes faster than other member function.
 It can be recursive.
 Its body does not contain if else, switch, loop, goto statement.
 The inline keyword is preceded by function definition.

Why inline function is used?


Whenever a function is called, control jumps to definition part of the function. During this jumping of
control, a significant amount of time is required. For functions having short definition if it is called
several time, huge amount of time will be lost. Therefore we declare such function as inline so that
when the function is called, rather than jumping to the definition of function, function definition is
expanded in a line wherever it is called.

Program 2.8 Write a program to find area of a circle using inline function.

Solution:
#include<iostream.h>
inline float area(int);
void main()
{
int r;
cout<<“ Enter the Value of r: ”;
cin>>r;
cout<<” Area is: “ << area(r);
}
inline float area (int a)
{
return(3.14*a*a);
}

Output:
Enter the Value of r:
7
153.86

40
11
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in

Friend Function

 Scope of a friend function is not inside the class in which it is declared.


 Since its scope is not inside the class, it cannot be called using the object of that class
 It can be called like a normal function without using any object.
 It cannot directly access the data members like other member function and it can access the
data members by using object through dot operator.
 It can be declared either in private or public part of the class definition.
 Usually it has the objects as arguments.
Program 2.9 Demonstration of Friend Function.

Solution:
#include<iostream.h>
class Add
{
int x, y, z;
public:
Add(int, int);
friend int calculate(Add p);
};

Add :: Add(int a, int b)


{
x=a;
y=b;
}
int calculate(Add p)
{
return(p.x+p.y);
}
void main()
{
Add a(5, 6);
cout<<calculate(a);
}

Output:
11

Note: Here the function calculate () is called directly like normal function as it is declared as friend.

41
12
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in

Friend Classes
It is possible for one class to be a friend of another class. When this is the case, the friend class and all of
its member functions have access to the private members defined within the other class.

#include <iostream.h>
class TwoValues
{
int a;
int b;
public:
TwoValues(int i, int j)
{
a = i;
b = j;
}
friend class Min;
};
class Min
{
public:
int min(TwoValues x);
};
int Min::min(TwoValues x)
{
return x.a < x.b ? x.a : x.b;
}
int main()
{
TwoValues ob(10, 20);
Min m;
cout << m.min(ob);
return 0;
}

Output:
10

Note: In this example, class Min has access to the private variables a and b declared within the
TwoValues class.

42
13
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in

Static Data Members

 The data member of a class preceded by the keyword static is known as static member.
 When we precede a member variable's declaration with static, we are telling the compiler that
only one copy of that variable will exist and that all objects of the class will share that variable.
Hence static variables are called class variables.
 Unlike regular data members, individual copies of a static member variable are not made for
each object. No matter how many objects of a class are created, only one copy of a static data
member exists. Thus, all objects of that class use that same variable.
 All static variables are initialized to zero before the first object is created.
 Normal data members are called object variable but static data members are called class
variables.

Program 2.11 Demonstration of static data members.

Solution:

#include<iostream.h>
class A
{
int p;
static int q;
public:
A();
void incr(void);
void display(void);
};
A :: A()
{
p=5;
}
int A:: q=10;
void A:: incr()
{
p++;
q++;
}
void A:: display()
{
cout<<p<<”\t”<<q<<endl;
}
void main()

43
14
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in

{
A a1, a2, a3;
a1.incr();
a1.display();
a2.incr();
a2.display();
a3.incr();
a3.display();
}

Output:
6 11
6 12
6 13

Note: Here p is a normal variable, whose value is 5 for all 3 objects a1, a2 and a3 (For each object,
separate copy of p exists). But q is static variable or member, whose initial value is 10 and a single copy
of q exists for all the objects.

Static Member function/method

 A static function can have access to only other static members (functions or variables) declared
in the same class. (Of course, global functions and data may be accessed by static member
functions.)
 It is accessed by class name and not by object’s name i.e. class-name::function-name;
 The function name is preceded by the keyword static.
 A static member function does not have this pointer.
 There cannot be a static and a non-static version of the same function.
 A static member function may not be virtual.
 Finally, they cannot be declared as const or volatile.

Program 2.12 Demonstration of static member function.

Solution:
#include<iostream.h>

class ABC
{
public:
static int add(int, int);
};
int ABC:: add(int a, int b)
{

44
15
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in

return(a+b);
}

void main()
{
ABC abc;
int res;
res=ABC :: add(30, 40);
cout<<res;
}

Output:
70

45
16
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in

Assignment 2

Short Type Questions

1. What is friend function? State its properties.


2. What is inline function?
3. What is static data members and static member function?
4. How a member function of a class can be accessed?
5. Differentiate between macros and inline function.
6. What are data members and member function?
7. Define copy constructor with an example.
8. Define default constructor with an example.
9. Define dynamic initialization of object. How it is achieved?
10. What is scope resolution operator? State any two applications.

Long Type Questions

1. Explain function prototype, calling and definition with suitable examples.


2. What do you mean by static data members? Discuss.
3. WAP to find greatest of 2 no’s using class and object
4. WAP to add two time objects (in the form of hh : mm :ss).
5. WAP to add two string object. The string object is initialized by following constructor. string
(char[]).
6. Define a class student with member variables as roll number and name. Generate an object and
initialize its variables using constructors and display them.
7. What is the difference between public, private and protected members of class?
8. What is a constructor? Explain about copy constructor with a suitable example.
9. What is a destructor? Explain with an example.
10. What is class and object? How a class differs from a structure?
11. Define a complex number. Write a program to read and print a complex number using class and
object.
12. What is default argument? Discuss with a suitable example.
13. A function can return more than one value. Explain.
14. What is the difference between method overriding and method overloading? Explain your
answer with suitable example.
15. How does an inline function differ from a preprocessor Macro?
16. Create a class called Employee which contains protected attributes such as emp_id, emp_salary
and emp_da. emp_da is 20% of the emp_salary. Provide an appropriate method to take user
input to initialize the attributes and display the details regarding 25 students of a class.
17. Write a complete program to create a class called Account with protected attributes such as
account number and balance. The attributes should be initialized through constructors. The
class contains a public method named as show () to display the initialized attributes. Provide a
mechanism to create an array of Account objects. The array size should be given by the user at
run time.
18. What is a copy constructor? Explain the role of a copy constructor while initializing a pointer
attribute of a class for which the memory allocation takes place at the run time.

46
17
Smartzworld.com jntuworldupdates.org
Smartworld.asia Specworld.in

Find Errors (if any) and correct them:


1. class My_College 3. class F
{ {
float cgpa; int p;
public: public:
float My_College(); friend void print(){ }
}; };
void main()
2. class ABCD {
{ print();
public: }
int INT() 4. class M
{ {
return(1); char nm[50];
} public:
}; show();
void main() };
{
cout<<INT();
}

Find Output:
1. #include<iostream.h> 3. #include<iostream.h>
int x=5; int x=5;
void main() void main()
{ {
int x=4; (5/2)? cout<<”Hi”:cout<<”Hello”;
cout<<x<<::x; }
}
4. #include<iostream.h>
2. #include<iostream.h> void main()
void main() {
{ int a, b;
int a=2, b=1; a=(b=7, b+2);
char x=1, y=0; cout<<a;
if(a, b, x, y) }
cout<<”Congratulations!!”;
}

47
18
Smartzworld.com jntuworldupdates.org

You might also like