codescracker


c++

C++ Classes and Objects



« Previous Tutorial Next Tutorial »


Classes and Objects are the most important features of C++. Let's start with class.

C++ Class

As you already know that a class represents a group of similar objects. A class is a way to bind the data describing an entity and its associated functions together. For instance, consider an account having characteristics account no, type, and balance. Its associated operations are deposit and withdrawal.

We can define its class as follows :

class Account
{
	int accountno;
	char type;
	float balance;
	float deposit(float amount)
	{
		balance = balance + amount;
		return balance;
	}
	float withdraw(float amount)
	{
		balance = balance - amount;
		return balance;
	}
};

See the data describing an account (i.e., account no, type & balance) and its associated operations (deposit and withdraw) are bound together under one name Account. Thus, Account makes a class. Now instances of the class Account can be created.

The main purpose of C++ programming is to add object orientation to the C programming language and classes are the central feature of C++ that supports object-oriented programming and are often called user-defined types.

A class is used to specify the form of an object and it combines data representation and methods for manipulating that data into one neat package. The data and functions within a class are called members of the class.

C++ Class Declaration

In C++, the declaration of a class involves declaration of its four associated attributes:

The class specification takes place in the following two parts:

C++ Class Definition

Here is the general form of the class definition:

class class-name
{
	private:
		[variable declarations;]
		[function declarations;]
	protected:
		[variable declarations;]
		[function declarations;]
	public:
		[variable declarations;]
		[function declarations;]
};

When you define a class, you define a blueprint for a data type. This doesn't actually define any data, but it does define what the class name means, that is, what an object of the class will consist of and what operations can be performed on such an object.

A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a list of declarations. For example, we defined the Box data type using the keyword class as follows:

class Box
{
   public:
      double length;   // Length of a box
      double breadth;  // Breadth of a box
      double height;   // Height of a box
};

The keyword public determines the access attributes of the members of the class that follow it. A public member can be accessed from outside the class anywhere within the scope of the class object. You can also specify the members of a class as private or protected which we will discuss in a sub-section.

C++ Class Method's Definition

Members functions can be defined in the following two places:

Class Method's Definition Outside the Class Definition

A member function definition outside the class definition is much the same as that of function definitions you are familiar with. Here, the only difference is that the name of the function is the full name of the function also called as qualified-name of a function which is written as:

class-name::function-name

Here class-name indicates that the function specified by function-name is a member of the class specified by class-name. And the symbol ::, called the scope resolution operator, specifies that the scope of the function is restricted to the class class-name. Here is the general form of a member function definition outside the class definition :

return-type class-name :: function-name(parameter list)
{
	.
	. function body
	.
}

Class Method's Definition Inside the Class Definition

In this case, you don't need to put the membership label along with the function name. For example, we could define the class student as shown here:

class student
{
	int rollno;
	char name[40];
	float marks;
	void readdata()
	{
		cout<<"Enter roll no: ";
		cin>>rollno;
		cout<<"Enter name: ";
		gets(name);
		cout<<"Enter marks: ";
		cin>>marks;
	}
};

C++ Class Example Programs

Here is an example program demonstrating the concept of classes in C++ practically.

/* C++ Classes and Objects - This C++ program
 * stores price list of 5 items and to print
 * the largest price as well as the sum of all
 * prices using class in C++ */

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class ITEM
{
	int itemcode[5];
	float itprice[5];
	public:
		void initialize(void);
		float largest(void);
		float sum(void);
		void displayitems(void);
};
void ITEM::initialize(void)
{
	for(int i=0; i<5; i++)
	{
		cout<<"Item No.: "<<(i+1);
		cout<<"\nEnter item code: ";
		cin>>itemcode[i];
		cout<<"Enter item price: ";
		cin>>itprice[i];
		cout<<"\n";
	}
}
float ITEM::largest(void)
{
	float larg=itprice[0];
	for(int i=1; i<5; i++)
	{
		if(larg<itprice[i])
		{
			larg=itprice[i];
		}
	}
	return larg;
}
float ITEM::sum(void)
{
	float sum=0;
	for(int i=0; i<5; i++)
	{
		sum = sum + itprice[i];
	}
	return sum;
}
void ITEM::displayitems(void)
{
	cout<<"\nCode\tPrice\n";
	for(int i=0; i<5; i++)
	{
		cout<<itemcode[i]<<"\t";
		cout<<itprice[i]<<"\n";
	}
}
void main()
{
	clrscr();
	ITEM order;
	order.initialize();
	float tot, big;
	int ch=0;
	do
	{
		cout<<"\nMain Menu\n";
		cout<<"1.Display Largest Price\n";
		cout<<"2.Display Sum of Prices\n";
		cout<<"3.Display Item List\n";
		cout<<"4.Exit\n";
		cout<<"Enter your choice(1-4): ";
		cin>>ch;
		switch(ch)
		{
			case 1:	big=order.largest();
				cout<<"Largest Price = "<<big;
				break;
			case 2:	tot=order.sum();
				cout<<"Sum of Prices = "<<tot;
				break;
			case 3:	order.displayitems();
				break;
			case 4: cout<<"Exiting...press any key...";
				getch();
				exit(1);
			default:cout<<"\nWrong choice..!!";
				break;
		}
		cout<<"\n";
	}while(ch>=1 && ch<=4);
	getch();
}

Here are the sample runs of the above C++ program. After running the above C++ program, enter the details like this:

c++ class

After entering the above details, press ENTER. Now select desired choice. Here are some sample runs:

c++ class constructor

c++ class example

C++ Scope Rules Pertaining to a Class

Here the following table summarizes all scope rules pertaining to a class in C++

Element Scope Description
Class
Global Global Scope This class type is globally available to all the functions within a program. So, the objects of this class type can be created from any function within the program.
Local Local Scope This class type is locally available to the function in which the class definition occurs. The objects of this class type can be created only within the function that defines this class type.
Object
Global Global Scope This object can be used anywhere in the program by any function.
Local Local Scope This object can be used only within function that declares it.
Class Members
Private Class Scope These members can be accessed only by the member functions of the class. These can't be accessed directly via objects.
Protected - do - - do -
Public Global for global objects, Local for local objects The scope of public members depends upon the referencing object. If the referencing object is local, the scope of public member is local. If the referencing object is global, the scope of public member is global.

Types of Class Functions

There are three types of class functions, given here:

Example

Here is an example program demonstrating the types of class functions in C++

/* C++ Classes and Objects - Example Program */

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#include<stdio.h>
class STUDENT
{
	private:
		int rollno;
		char name[40];
		float marks;
		char grade;
	public:
		void read()			// mutator
		{
			cout<<"\nEnter rollno: ";
			cin>>rollno;
			cout<<"Enter name: ";
			gets(name);
			cout<<"Enter marks: ";
			cin>>marks;
		}
		void display()		// accessor
		{
			calculategrade();
			cout<<"Roll no.: "<<rollno<<"\n";
			cout<<"Name: "<<name<<"\n";
			cout<<"Marks: "<<marks<<"\n";
			cout<<"Grade: "<<grade<<"\n";
		}
		int getrollno()		// accessor
		{
			return rollno;
		}
		float getmarks()	// accessor
		{
			return marks;
		}
		void calculategrade()	// mutator
		{
			if(marks>=80)
			{
				grade = 'A';
			}
			else if(marks>=60)
			{
				grade = 'B';
			}
			else if(marks>=40)
			{
				grade = 'C';
			}
			else
			{
				grade = 'F';
			}
		}
};
void main()
{
	clrscr();
	STUDENT tw[5];
	for(int i=0; i<5; i++)
	{
		cout<<"\nEnter details for Student "<<i+1<<": ";
		tw[i].read();
	}
	int choice, rno, pos=-1, highmarks=0;
	do
	{
		cout<<"\nMain Menu\n";
		cout<<"1.Specific Student\n";
		cout<<"2.Topper\n";
		cout<<"3.Exit\n";
		cout<<"Enter youce choice(1-3): ";
		cin>>choice;
		switch(choice)
		{
			case 1:
				cout<<"Enter roll no of student whose details you want to know/see: ";
				cin>>rno;
				for(i=0; i<5; i++)
				{
					if(tw[i].getrollno()==rno)
					{
						tw[i].display();
						break;
					}
				}
				if(i==5)
				{
					cout<<"Invalid rollno..!!";
				}
				break;
			case 2:
				for(i=0; i<5; i++)
				{
					if(tw[i].getmarks()>highmarks)
					{
						pos=i;
						highmarks=tw[i].getmarks();
					}
				}
				tw[pos].display();
				break;
			case 3:
				cout<<"Exiting..press a key..";
				getch();
				exit(1);
			default:
				cout<<"Wrong choice..!!";
				break;
		}
	}while(choice>=1 && choice<=3);
	getch();
}

Here are the sample runs of the above C++ program. Run the above program, and enter the details like this:

c++ class tutorial

After entering the details as shown in the above figure, just press ENTER and choose the desired options as shown in these sample outputs:

c++ class programs

c++ class inheritance

Nested Classes in C++

Here is an example program demonstrating the concept of nested classes in C++

/* C++ Classes and Objects - Example Program */

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class OUTER
{
	int a;
	class INNER
	{
		int b;
		public:
			int c;
			void print(void)
			{
				cout<<"\nINNER::print()"<<"\n";
				cout<<"b("<<b<<"), c("<<c<<")\n";
			}
			INNER()
			{
				b=5;
				c=10;
			}
	};
	INNER iobj1;
	public:
		INNER iobj2;
		void second(void)
		{
			cout<<"\nOUTER::second()\n";
			cout<<iobj2.c<<"\n";
			cout<<"A = "<<a<<"\n";
			iobj1.print();
		}
		OUTER()
		{
			a=25;
		}
};
void main()
{
	clrscr();
	OUTER oobj;
	oobj.second();
	oobj.iobj2.print();
	getch();
}

Here is the sample run of the above C++ program:

c++ nested class

C++ Scope Resolution Operator

The following program illustrates functioning of scope resolution operator:

/* C++ Classes and Objects - Example Program */

#include<iostream.h>
#include<conio.h>
int a=100;
void main()
{
	clrscr();
	int a=150;
	cout<<"main()\n";
	cout<<"a = "<<a<<"\n";
	cout<<"::a = "<<::a<<"\n\n";

	{
		int a=250;
		cout<<"Inner Block\n";
		cout<<"a = "<<a<<"\n";
		cout<<"::a = "<<::a<<"\n\n";
	}

	cout<<"Back to main()\n";
	cout<<"a = "<<a<<"\n";
	cout<<"::a = "<<::a<<"\n";
	getch();
}

Here is the sample run of this C++ program:

c++ scope resolution operator

C++ Object

When you define a class, it doesn't define or create objects of that class, rather it only specifies what types of information the objects of this class type wil be containing.

Define C++ Objects

A class provides the blueprints for objects, so basically an object is created from a class. We declare objects of a class with exactly the same sort of declaration that we declare variables of basic types. Following statements declare two objects of class Box:

Box Box1;          // Declare Box1 of type Box
Box Box2;          // Declare Box2 of type Box

Both of the objects Box1 and Box2 will have their own copy of data members.

Accessing the Data Members

The public data members of objects of a class can be accessed using the direct member access operator (.). Let us try the following example to make the things clear:

/* C++ Classes and Objects - Example Program */

#include<iostream.h>
#include<conio.h>
class Box
{
	public:
		double leng;   // Length of a box
		double brea;   // Breadth of a box
		double heig;   // Height of a box
};
void main()
{
	clrscr();
	Box box1obj;        // Declared box1obj of type Box
	Box box2obj;        // Declared box2obj of type Box
	double volume = 0.0;     // Store the volume of a box here

	// box 1 specification
	box1obj.heig = 5.0;
	box1obj.leng = 6.0;
	box1obj.brea = 7.0;

	// box 2 specification
	box2obj.heig = 10.0;
	box2obj.leng = 12.0;
	box2obj.brea = 13.0;

	// calculate volume of box 1
	volume = box1obj.heig * box1obj.leng * box1obj.brea;
	cout<<"Volume of Box1 = "<<volume<<"\n";

	// calculate volume of box 2
	volume = box2obj.heig * box2obj.leng * box2obj.brea;
	cout<<"Volume of Box2 = "<<volume<<"\n";

	getch();
}

Here is the sample output of the above C++ program

c++ object

It is important to note that private and protected members can not be accessed directly using direct member access operator (.). We will learn how private and protected members can be accessed.

Array of Objects

Here is an example program illustrates the use of object arrays in C++

/* C++ Classes and Objects - Example Program */

#include<iostream.h>
#include<conio.h>
class ITEM
{
	int itemno;
	float price;
	public:
		void getdata(int i, float f)
		{
			itemno=i;
			price=f;
		}
		void putdata(void)
		{
			cout<<"Itemno: "<<itemno<<"\t";
			cout<<"Price: "<<price<<"\n\n";
		}
};
ITEM order[5];
void main()
{
	clrscr();
	int ino;
	float cost;
	for(int z=0; z<5; z++)
	{
		cout<<"Enter itemno and itemprice for item "<<z+1<<"\n";
		cin>>ino>>cost;
		order[z].getdata(ino, cost);
	}
	cout<<"\n";
	for(z=0; z<5; z++)
	{
		cout<<"Item "<<z+1<<"\n";
		order[z].putdata();
	}
	getch();
}

Here are the sample runs of this C++ program. Run this C++ program and enter the details like this:

c++ object definition

Now after entering the details, press ENTER and here is the output:

c++ classes and objects

Objects as Function Arguments in C++

Here is an example program to illustrates the use of objects as arguments to member, and nonmember function using call by value mechanism in C++

/* C++ Classes and Objects - Example Program */

#include<iostream.h>
#include<conio.h>
class TIME
{
	int hrs, mins, secs;
	public:
		int totsecs;
		void gettime(int h, int m, int s)
		{
			hrs=h;
			mins=m;
			secs=s;
			totsecs=(hrs*60)+(mins*60)+secs;
		}
		void puttime(void)
		{
			cout<<"Time is: "<<hrs<<":"<<mins<<":"<<secs<<"\n";
		}
		void convert(TIME t, char ch);
		void sum(TIME t1, TIME t2);
		int gethrs()
		{
			return hrs;
		}
		int getmins()
		{
			return mins;
		}
		int getsecs()
		{
			return secs;
		}
};
void TIME::convert(TIME t, char ch)
{
	switch(ch)
	{
		case 'h':
			cout<<"Time in hours is: "<<t.hrs<<":"<<t.mins<<":"<<t.secs<<" hrs\n";
			break;
		case 'p':
			cout<<"Time in am/pm is: "<<((t.hrs>12)?(t.hrs-12):t.hrs)<<":"<<t.mins<<":"<<t.secs;
			cout<<((t.hrs>12)?"pm":"am")<<"\n";
			break;
		default:
			cout<<"Wrong choice..!!\n";
	}
}
void TIME::sum(TIME t1, TIME t2)
{
	int h, m, s, sq, mq;
	sq=(t1.secs+t2.secs)/60;
	s=(t1.secs+t2.secs)%60;
	mq=(sq+t1.mins+t2.mins)/60;
	m=(sq+t1.mins+t2.mins)%60;
	h=mq+t1.hrs+t2.hrs;
	if(h==24) h=0;
		cout<<"Total time is: "<<h<<":"<<m<<":"<<s<<"\n";
}
void prnvalues(TIME t1)
{
	cout<<"Total secs: "<<t1.totsecs;
	cout<<"\n";
}
void main()
{
	clrscr();
	TIME tm1, tm2;
	int tt;
	char ch;
	tm1.gettime(5, 13, 27);
	tm2.gettime(7, 48, 38);
	cout<<"Enter h to convert in hours format, p for am/pm format: ";
	cin>>ch;
	tm1.convert(tm2, ch);
	tm1.sum(tm1, tm2);
	prnvalues(tm2);
	getch();
}

Here are the two sample runs of the above C++ program:

c++ objects and classes

classes and objects in c++

Here is the program to illustrates the call by reference mechanism on objects

/* C++ Classes and Objects - Example Program */

#include<iostream.h>
#include<conio.h>
#include<string.h>
class TIME
{
	int hrs, mins, secs;
	char suf[4];
	public:
		int totsecs;
		void gettime(int h, int m, int s)
		{
			hrs=h;
			mins=m;
			secs=s;
			totsecs=(hrs*60)+(mins*60)+secs;
			strcpy(suf, "Hrs");
		}
		void puttime(void)
		{
			cout<<"Time is: "<<hrs<<":"<<mins<<":"<<secs<<" "<<suf<<"\n";
		}
		char *getsuf()
		{
			return suf;
		}
		void convert(TIME &t, char ch);
		void sum(TIME &t1, TIME &t2);
		int gethrs()
		{
			return hrs;
		}
		int getmins()
		{
			return mins;
		}
		int getsecs()
		{
			return secs;
		}
};
void TIME::convert(TIME &t, char ch)
{
	switch(ch)
	{
		case 'h':
			if(strcmp(t.suf, "Hrs")!=0)
			{
				t.hrs=(strcmp(t.suf, "am")==0)?t.hrs:t.hrs+12;
				strcpy(t.suf,"Hrs");
			}
			cout<<"Time in hours is: "<<t.hrs<<":"<<t.mins<<":"<<t.secs<<" "<<t.suf<<"\n";
			break;
		case 'p':
			if(strcmp(t.suf,"Hrs")==0)
			{
				(t.hrs>12)?strcpy(t.suf,"pm"):strcpy(t.suf,"am");
				t.hrs=((t.hrs>12)?(t.hrs-12):t.hrs);
			}
			cout<<"Time in am/pm is: "<<t.hrs<<":"<<t.mins<<":"<<t.secs<<" "<<t.suf<<"\n";
			break;
		default:
			cout<<"Wrong choice..!!";
			break;
	}
}
void TIME::sum(TIME &t1, TIME &t2)
{
	int h, m, s, sq, mq;
	if(strcmp(t1.getsuf(),"pm")==0)
	{
		convert(t1,'h');
	}
	if(strcmp(t2.getsuf(),"pm")==0)
	{
		convert(t2,'h');
	}
	sq=(t1.secs+t2.secs)/60;
	s=(t1.secs+t2.secs)%60;
	mq=(sq+t1.mins+t2.mins)/60;
	m=(sq+t1.mins+t2.mins)%60;
	h=mq+t1.hrs+t2.hrs;
	if(h==24) h=0;
		cout<<"Total time is: "<<h<<":"<<m<<":"<<s<<"Hrs\n";
}
void prnvalues(TIME &t1)
{
	cout<<"hrs:"<<t1.gethrs()<<"\n";
	cout<<"mins:"<<t1.getmins()<<"\n";
	cout<<"secs:"<<t1.getsecs()<<"\n";
	cout<<"Total secs:"<<t1.totsecs<<"\n";
}
void main()
{
	clrscr();
	TIME tm1, tm2;
	char ch;
	tm1.gettime(15,13,27);
	tm2.gettime(7,48,38);
	cout<<"Enter h to convert in hours format, or p for am/pm format: ";
	cin>>ch;
	cout<<"Converted times are:\n";
	cout<<"Time 1: ";
	tm1.convert(tm1,ch);
	cout<<"Time 2: ";
	tm2.convert(tm2,ch);
	tm1.sum(tm1, tm2);
	prnvalues(tm2);
	getch();
}

Below are the two sample outputs of the above C++ program:

object and classes in c++

object as function arguments

Function Returning Objects

Here is an example program demonstrates the working of a function returning an object

/* C++ Classes and Objects - Example Program */

#include<iostream.h>
#include<conio.h>
class DISTANCE
{
	int feet, inches;
	public:
		void getdata(int f, int i)
		{
			feet=f;
			inches=i;
		}
		void print(void)
		{
			cout<<feet<<" feet "<<inches<<" inches \n";
		}
		DISTANCE sum(DISTANCE d2);
};
DISTANCE DISTANCE::sum(DISTANCE d2)
{
	DISTANCE d3;
	d3.feet=feet+d2.feet+(inches+d2.inches)/12;
	d3.inches=(inches+d2.inches)%12;
	return d3;
}
void main()
{
	clrscr();
	DISTANCE len1, len2, tot;
	len1.getdata(17, 6);
	len2.getdata(13, 8);
	tot=len1.sum(len2);
	cout<<"Length1: ";
	len1.print();
	cout<<"Length2: ";
	len2.print();
	cout<<"Total Length: ";
	tot.print();
	getch();
}

Following is the sample output of this C++ program:

function returning objects

Static Members in C++

Here is an example program, to keep count of created objects using static members in C++

/* C++ Classes and Objects - Example Program */

#include<iostream.h>
#include<conio.h>
class X
{
	int codeno;
	float price;
	static int count;
	public:
		void getval(int i, float j)
		{
			codeno=i;
			price=j;
			count++;
		}
		void display(void)
		{
			cout<<"Code no: "<<codeno<<"\t";
			cout<<"Price: "<<price<<"\n";
		}
		static void dispcount(void)
		{
			cout<<"count = "<<count<<"\n";
		}
};
int X::count=0;
void main()
{
	clrscr();
	X obj1, obj2;
	obj1.getval(201, 35.12);
	obj2.getval(202, 48.42);
	X::dispcount();
	X obj3;
	obj3.getval(203, 59.00);
	X::dispcount();
	obj1.display();
	obj2.display();
	obj3.display();
	getch();
}

Here is the output produced by the above C++ program:

static members

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test