Professional Documents
Culture Documents
Declaring Objects
When a class is defined, only the specification for the object is defined; no memory or storage is
allocated. To use the data and access functions defined in the class, you need to create objects.
Syntax
ClassName ObjectName;
Accessing data members and member functions: The data members and member functions of the
class can be accessed using the dot(„.‟) operator with the object. For example, if the name of the
object is obj and you want to access the member function with the name printName() then you will
have to write obj.printName().
Access to class members: The object can access the public data member and member functions
1 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP
OBJECT ORIENTED PROGRAMMING LANGUAGE
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:
Employee e, *a;
e.readData();
Where e is an object and readData() is a member function. The dot operator is used
because a is a simple object.
In statement
a->readData();
*a is pointer to class item; therefore, the arrow operator is used to access the member.
Access Specifiers:
1. Public: The keyword public can be used to allow objects to access the member variables
of a class directly like structures in C.
2. Private: The private keyword is used to prevent direct access of member variables by the
object. The class by default produces this effect. i.e., a data member can only be
accessed by the member functions of the class.
3. Protected: The members which are declared under protected section, can be accessed by
the member functions of the class and those of the class which is immediately
derived from it. No other class can access the protected data elements.
// Data Members
string geekname;
// Member Functions()
void printname() { cout << "Geekname is:" << geekname; }
};
int main()
{
// Declare an object of class geeks
Geeks obj1;
// accessing data member
obj1.geekname = "Abhi";
// accessing member function
obj1.printname();
return 0;
}
Output
Geekname is:Abhi
membership “Identity label” in the header. This labels tells the compiler which class the function
belongs to.
The general form of a member function definition outside the class is:
The membership label class-name:: tells the compiler that the function function-name belongs to
the class class-name. That is, the scope of the function is restricted to the class-name specified in
the header line. The symbol :: is called the scope resolution operator.
For instance, consider the member functions getdata() and putdata(). They may be coded
(outside the class item) as follows:
Since, these functions do not return any value, their return-type is void.
Note:
1) Several different classes can use the same function name. The membership label will resolve
their scope
2) Member functions can access the private data of the class. A non-member function cannot do
so. (However, an exception to this rule is a friend function discussed later)
3) A member function can call another member function directly, without using the dot operator
(The use of dot operator in case of class is discussed later)
2. Inside the Class Definition:
Another method of defining a member function is to replace the function declaration by the
actual function definition inside the class. For example, we could define the item class as
follows:
class item
{
int number;
float cost;
public:
void getdata(int a, float b) //declaration
void putdata() //definition
{ //inline function
cout << "Number :" << number << endl;
cout << "Cost :" << cost << endl;
}
When a function is defined inside a class, it is treated as an inline function. Therefore, all the
restrictions and limitations that apply to an inline function are also applicable here.
A data member of a class can be qualified as static. A static member variable has certain special
characteristics. These are:
Syntax:
#include <iostream>
using namespace std;
class item
{
static int count;
int number;
public:
void getdata(int a)
{
number = a;
count ++;
}
void getcount(void)
{
cout << "Count: "<< count <<"\n";
}
};
int item :: count;
int main()
{
item a,b,c;
a.getcount();
b.getcount();
c.getcount();
a.getdata(100);
b.getdata(200);
c.getdata(300);
a.getcount();
b.getcount();
Output:
c.getcount(); Count: 0
return 0; Count: 0
} Count: 0
After reading data
Count: 3
Count: 3
Count: 3
static Member Functions
Like member variables, function can also be declared as static. When a function is defined as
static, it can access only static member variables and functions of the same class. The not-static
members are not available to these functions. The static member function declared in public
section can be invoked using its class name without using its objects. The programmer must
follow the following points while declaring static function:
1. Just one copy of a static member is created in the memory for entire class. All objects of
the class share the same copy of static member.
2. static member function can access only static data members or functions.
3. A static member function can be called with the class name as follows:
class-name :: function-name;
class-name :: function-name;
In the following code the static function getcount() displays the number of objects created
till that moment.
#include <iostream>
using namespace std;
class item
{
static int count;
int number;
public:
void getdata(int a)
{
number = a;
count ++;
}
void getcount(void)
{
cout << "Count: "<< count <<"\n";
}
static void show_count()
{
cout << "Count: "<< count <<"\n";
}
};
int item :: count;
int main()
{
item a,b,c;
item::show_count();
a.getdata(100);
b.getdata(200);
c.getdata(300);
item::show_count();
return 0;
}
Output:
Count: 0
After reading data
Count: 3
2.4 Array of Objects in C++ with Examples:
Example:
Let‟s consider an example of taking random integers from the user.
Array
Array of Objects
When a class is defined, only the specification for the object is defined; no memory or storage is
allocated. To use the data and access functions defined in the class, you need to create objects.
Syntax:
ClassName ObjectName[number of objects];
The Array of Objects stores objects. An array of a class type is also known as an array of objects.
Example#1:
Storing more than one Employee data. Let‟s assume there is an array of objects for storing
employee data emp[50].
C++
class Employee
{
int id;
char name[30];
public:
void getdata();//Declaration of function
void putdata();//Declaration of function
};
void Employee::getdata(){//Defining of function
cout<<"Enter Id : ";
cin>>id;
cout<<"Enter Name : ";
cin>>name;
}
void Employee::putdata(){//Defining of function
cout<<id<<" ";
cout<<name<<" ";
cout<<endl;
}
int main(){
Employee emp; //One member
emp.getdata();//Accessing the function
emp.putdata();//Accessing the function
return 0;
The main concept of OOP paradigm is data hiding and data encapsulation. Whenever data
variables are declared in a private category of a class, these members are restricted from
accessing by non-member functions. The private data values can be neither read nor written by
non-member functions. If an attempt is made directly to access these members, the compiler will
display an error message “inaccessible data type”. The best way to access private member is to
change access specifier to public group. But it violates the concept of data hiding. To solve this
problem, a friend function/class can be declared to have access these data members. Friend is a
special mechanism for letting non-member functions access private data. The keyword friend
inform the compiler it is not a member of the class.
{ {
public: return n;
myclass(int,int); void }
printvalues();
int main() {
friend int sum(myclass);
myclass m(10,20);
}; m.printvalues();
cout<<"Sum of values in
myclass::myclass(int n1,int n2)
object:"<<sum(m)<<endl;
{
return 0;
num1=n1;
num2=n2; }
#include <iostream>
using namespace std;
class myclass
{
int num1,num2;
public:
myclass(int,int); void printvalues();friend class math;
};
myclass::myclass(int n1,int n2)
{
num1=n1;num2=n2;
}
void myclass::printvalues()
{
cout<<"first value is:"<<num1<<endl;cout<<" second is:"<<num2<<endl;
}
class math
{
public:
int sum(myclass);
int multiply(myclass);
};
int math::sum(myclass obj)
{
return obj.num1+obj.num2;
}
int math::multiply(myclass obj)
{
return obj.num1*obj.num2;
}
int main() {
myclass mc(10,20); math m;
cout<<"The sum of two values in myclass object:"<<m.sum(mc)<<endl;
cout<<"The multiplication of two values in myclass object:"<<m.multiply(mc)<<endl;
return 0;
}
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.
1. class class_name
2. {
3. friend data_type function_name(argument/s); // syntax of friend function.
4. };
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.
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.
Let's see the simple example of C++ friend function used to print the length of a box.
1. #include <iostream>
2. using namespace std;
3. class Box
4. {
13 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP
OBJECT ORIENTED PROGRAMMING LANGUAGE
5. private:
6. int length;
7. public:
8. Box(): length(0) { }
9. friend int printLength(Box); //friend function
10. };
11. int printLength(Box b)
12. {
13. b.length += 10;
14. return b.length;
15. }
16. int main()
17. {
18. Box b;
19. cout<<"Length of box: "<< printLength(b)<<endl;
20. return 0;
21. }
Output:
Length of box: 10
2.6 C++ Overloading (Function and Operator)
If we create two or more members having the same name but different in number or type of
parameter, it is known as C++ overloading. In C++, we can overload:
o methods,
o constructors, and
o indexed properties
o Function overloading
o Operator overloading
Function Overloading is defined as the process of having two or more function with the same name,
but different in parameters is known as function overloading in C++. In function overloading, the
function is redefined by using either different types of arguments or a different number of arguments.
It is only through these differences compiler can differentiate between the functions.
The advantage of Function overloading is that it increases the readability of the program because
you don't need to use different names for the same action.
Let's see the simple example of function overloading where we are changing number of arguments of
add() method.
1. #include <iostream>
2. using namespace std;
3. class Cal {
4. public:
5. static int add(int a,int b){
6. return a + b;
7. }
8. static int add(int a, int b, int c)
9. {
10. return a + b + c;
11. }
12. };
13. int main(void) {
15 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP
OBJECT ORIENTED PROGRAMMING LANGUAGE
Output:
30
55
Let's see the simple example when the type of the arguments vary.
1. #include<iostream>
2. using namespace std;
3. int mul(int,int);
4. float mul(float,int);
5.
6.
7. int mul(int a,int b)
8. {
9. return a*b;
10. }
11. float mul(double x, int y)
12. {
13. return x*y;
14. }
15. int main()
16. {
17. int r1 = mul(6,7);
18. float r2 = mul(0.2,3);
19. std::cout << "r1 is : " <<r1<< std::endl;
20. std::cout <<"r2 is : " <<r2<< std::endl;
21. return 0;
22. }
Output:
r1 is : 42
r2 is : 0.6
When the compiler is unable to decide which function is to be invoked among the overloaded
function, this situation is known as function overloading.
When the compiler shows the ambiguity error, the compiler does not run the program.
o Type Conversion.
o Function with default arguments.
o Function with pass by reference.
o Type Conversion:
1. #include<iostream>
2. using namespace std;
3. void fun(int);
4. void fun(float);
5. void fun(int i)
6. {
7. std::cout << "Value of i is : " <<i<< std::endl;
8. }
17 | DEPARTMENT OF COMPUTER APPLICATION –RASC- N.MANIMOZHI- AP
OBJECT ORIENTED PROGRAMMING LANGUAGE
9. void fun(float j)
10. {
11. std::cout << "Value of j is : " <<j<< std::endl;
12. }
13. int main()
14. {
15. fun(12);
16. fun(1.2);
17. return 0;
18. }
The above example shows an error "call of overloaded 'fun(double)' is ambiguous". The fun(10)
will call the first function. The fun(1.2) calls the second function according to our prediction. But,
this does not refer to any function as in C++, all the floating point constants are treated as double not
as a float. If we replace float to double, the program works. Therefore, this is a type conversion from
float to double.
1. #include<iostream>
2. using namespace std;
3. void fun(int);
4. void fun(int,int);
5. void fun(int i)
6. {
7. std::cout << "Value of i is : " <<i<< std::endl;
8. }
9. void fun(int a,int b=9)
10. {
11. std::cout << "Value of a is : " <<a<< std::endl;
12. std::cout << "Value of b is : " <<b<< std::endl;
13. }
14. int main()
15. {
16. fun(12);
17.
18. return 0;
19. }
The above example shows an error "call of overloaded 'fun(int)' is ambiguous". The fun(int a, int
b=9) can be called in two ways: first is by calling the function with one argument, i.e., fun(12) and
another way is calling the function with two arguments, i.e., fun(4,5). The fun(int i) function is
invoked with one argument. Therefore, the compiler could not be able to select among fun(int i) and
fun(int a,int b=9).
1. #include <iostream>
2. using namespace std;
3. void fun(int);
4. void fun(int &);
5. int main()
6. {
7. int a=10;
8. fun(a); // error, which f()?
9. return 0;
10. }
11. void fun(int x)
12. {
13. std::cout << "Value of x is : " <<x<< std::endl;
14. }
15. void fun(int &b)
16. {
17. std::cout << "Value of b is : " <<b<< std::endl;
18. }
The above example shows an error "call of overloaded 'fun(int&)' is ambiguous". The first
function takes one integer argument and the second function takes a reference parameter as an
argument. In this case, the compiler does not know which function is needed by the user as there is no
syntactical difference between the fun(int) and fun(int &).
The advantage of Operators overloading is to perform different operations on the same operand.
Where the return type is the type of value returned by the function.
operator op is an operator function where op is the operator being overloaded, and the operator is the
keyword.
o Existing operators can only be overloaded, but the new operators cannot be overloaded.
o The overloaded operator contains atleast one operand of the user-defined data type.
o We cannot use friend function to overload certain operators. However, the member function
can be used to overload those operators.
o When unary operators are overloaded through a member function take no explicit arguments,
but, if they are overloaded by a friend function, takes one argument.
o When binary operators are overloaded through a member function takes one explicit
argument, and if they are overloaded through a friend function takes two explicit arguments.
Let's see the simple example of operator overloading in C++. In this example, void operator ++ ()
operator function is defined (inside Test class).
1. #include <iostream>
2. using namespace std;
3. class Test
4. {
5. private:
6. int num;
7. public:
8. Test(): num(8){}
9. void operator ++() {
10. num = num+2;
11. }
12. void Print() {
13. cout<<"The Count is: "<<num;
14. }
15. };
16. int main()
17. {
18. Test tt;
19. ++tt; // calling of a function "void operator ++()"
20. tt.Print();
21. return 0;
22. }
Output:
1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. int x;
6. public:
7. A(){}
8. A(int i)
9. {
10. x=i;
11. }
12. void operator+(A);
13. void display();
14. };
19. }
20. int main()
21. {
22. A a1(5);
23. A a2(4);
24. a1+a2;
25. return 0;
26. }
Output:
Bit-Field
When we declare the members in a struct and classes, a pre-determined size is allocated for the
member variables. In C++, we can compress that allocated size using bit fields.
Bit Field is a feature in C++ for specifying the size of struct and class members so that they occupy
a specific number of bits, not the default memory size.
struct StructName {
dataType fieldName : width;
// more bit-field members...
};
class ClassName {
public:
dataType fieldName : width;
// more bit-field members...
};
where width is the number of bits.
class ClassName {
public:
dataType fieldName : width;
// more bit-field members...
};
where width is the number of bits.
Note: It is to be noted that bit fields are only acceptable for integral data types.
In the below example, we have used bit fields with classes instead of struct.
C++
int main()
{
Loan loan1;
loan1.principal = 500000;
loan1.interestRate = 15;
loan1.period = 36;
return 0;
}
Output
4 Bytes
2.7 Constructors:
while it is declared.
Characteristics of constructors:
(1) Constructor has the same name as that of the class it belongs.
(2) It should be a public member.
(3) It is invoked implicitly at the time of creation of the objects.
(4) Constructors have neither return value nor void.
(5) The main function of constructor is to initialize objects.
(6) Constructor can have default and can be overloaded.
(7) The constructor without arguments is called as default constructor.
Types of Constructors:
1. Default constructor
2. Parameterized constructor
3. Copy constructor
4. Dynamic Constructor
Default Constructor:
A constructor which does not take any arguments is called the default constructor. Suppose A
is a class, the default constructor in the class takes the following form:
A()
{
Statements;
}
The statements within the body of the function assign the values to the member data of the class.
Note that the name of the constructor is same as the class name and no return type is specified
not even void.
Example:
public:
construct(); int main() {
void display();
}; construct dc;
construct::construct() dc.display();
{ return 0;
x=10; }
y=20;
}
Parameterized Constructor: The constructor that can take arguments are called parametrized
constructors.
Example:
When more than one constructor is defined in a class, we say that constructor is overloaded.
{ y=val2;
int x;
int y; }
public: void construct::display()
construct(); {
construct(int); cout<<"The first value is:"<<x<<endl;
construct(int,int); cout<<"The second value
void display(); is:"<<y<<endl;
}; }
construct::construct()
{ int main() {
x=10;y=20;
} construct obj1;
construct::construct(int val1) construct obj2(100);
{ construct obj3(100,200);
x=val1; //object 1
y=20; obj1.display();
} //object 2
obj2.display();
//object 3
obj3.display();
return 0;
}
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:
class construct }
{ void construct::display()
int x; {
int y; cout<<"The first value is:"<<x<<endl;
public: cout<<"The second value
construct(int,int); is:"<<y<<endl;
construct(construct &); }
void display();
}; int main() {
construct::construct(int val1,int val2)
{ construct obj1(10,20);
Dynamic Constructor:
Sometimes we may require to dynamically allocate memory for objects during their creation.
This is done with the help of dynamic constructors. The dynamic constructors use the new
operator to allocate memory for objects during runtime. A Constructor which allocates memory
and initializes an object during runtime is called a dynamic constructor.
Example:
Class Dynamic
{ int *a;
public:
Dynamic(int n)
{
a=new int[n];
}
};
Here, the member data a of the class Dynamic is a pointer to int type. The constructor takes an
argument n of int type and allocates memory for n integers. The address of the first element in
the dynamic array is assigned to the pointer a.
Example:
#include <iostream>
using namespace std;
class integer
public:
{
int *a;
int n;
}
integer(int m)
void display()
{
n=m;
a=new int[m];
int i;
for(i=0;i<n;i++)
cout<<a[i]<<endl;
void accept()
{
int i;
for(i=0;i<n;i++)
cin>>a[i];
}
};
int main() {
integer v(5),v1(10);
cout<<"Enter elements";
v.accept();
cout<<"Display elements";
v.display();
cout<<"Enter elements";
v1.accept();
cout<<"Display elements";
v1.display();
return 0;
Destructors:
A destructor is defined to be a special member function of a class, which helps in releasing the
memory occupied by an object when it goes out of scope.
Characteristics:
1. It should be public member
2. The name of the destructor should as that of class name and it is preceded with ~.
3. It cannot take any arguments
4. No return type should be specified including void.
5. delete operator is to be used to de-allocate the memory allocated by new operator in the
constructor.
Example:
#include <iostream>
using namespace std;
int count=0;
class integer
{
int x;
public:
integer(int y)
{
count++;
cout<<"object"<<count<<"created<<endl";
x=y;
}
~integer()
{
cout<<"object -"<<count<<" destroyed"<<endl;
count--;
}
};
int main() {
integer a(10),b(20); Output:Object 1 created
return 0; Object 2 created
} Object -2 destroyed
object -1 destroyed
Static data members are class members that are declared using static keywords. A static member
has certain special characteristics which are as follows:
Only one copy of that member is created for the entire class and is shared by all the objects of
that class, no matter how many objects are created.
It is initialized before any object of this class is created, even before the main starts.
It is visible only within the class, but its lifetime is the entire program.
Syntax:
static data_type data_member_name;
Below is the C++ program to demonstrate the working of static data members:
C++
class A {
public:
A()
{
cout << "A's Constructor Called " <<
endl;
}
};
class B {
static A a;
public:
B()
{
cout << "B's Constructor Called " <<
endl;
}
};
// Driver code
int main()
{
B b;
return 0;
}
Output
Destructors
A Destructor is the opposite of Constructor, and needless to tell you that it has the opposite
effect. A constructor is automatically called to initialize a newly-created object. Conversely, a
destructor is automatically called when an object is destroyed to de-allocate the memory portion
that was allocated to the object on its creation.
A Destructor must:
Have the same name as its class, but will be preceded with a tilde ~
Neither have a return value nor arguments.
C++ has another type of member variables: the static member variables. Within a class
definition, if a variable is declared as static, only one copy of that variable is created for the
class, regardless of the number of objects instantiated. Static member variables provide a pretty
way to share data between objects of the same class. One common use for static data is to
maintain the number of objects created in one class.
Example
The following program uses static member variable to keep track on the number of objects
defined.
Example
The following program uses static member variable to keep track on the number of
objects defined in destructor.
#include <conio.h>
#include <iostream.h>
class test
{
static int objcount;
public:
test()
{ objcount++;
To use a static member variable, two distinct statements are needed: one inside the class for
the variable declaration:
int test::objcount=0;
The defined static variable objcount is incremented each time a new object is created. To do
this, the following statement is used inside the class constructor:
objcount++;
To get the value of static member variable objcount, the member function getcount() is called:
t1.getcount()
In the above statement, the member getcount() that is associated with the object t1 is called.
After defining objects t2 and t3, either of the three objects t1, t2, or t3 could be used in the
second function call.
One final note regarding the use of the :: operator: it is called the scope resolution operator.
This operator is used to specify the class to which a variable or a function belongs. This is
useful when defining a member function or a static variable outside the class definition.
Summary
In this article, we have continued our journey with Object-oriented programming by talking
about Destructors and Static Member Variables.
An object can be initialized using another object of the same class. There are two syntax
forms to achieve this.
A Destructor is the opposite of Constructor. It de-allocates memory allocated to an object that
is no longer needed.
A Static member variable is created once for an entire class. It provides a way to share data
between objects of the same class.