Docsity

C++ Programming – Chapter: Classes & Objects | Complete Diploma IT Notes with Programs, Study notes of Object Oriented Programming

Toggle sidebar
bg1
Chapter 02. Classes & Objects
Class
Class is a way to bind data and its associated functions together. Class
can also be defined as user defined data type that contains data members
and member functions in it. So, class is a blueprint for object. That is, it
defines what an object of the class will consist of and what operations can
be performed on such an object.
Specifying a Class
Generally, a class specification has two parts:
1. Class declaration
2. Class function definitions
Class declaration syntax:
class class_name
{
private:
variable declarations;
function declarations;
public:
variable declarations;
function declarations;
};
Objects
Objects are the basic unit of OOP. They are instances of class, in which
data members and various member functions that operate on data are
bundled as a unit called as object.
Creating Objects
Once a class is declared, we can create variables of that type by using the
class name, like any other built-in type variable.
Objects can also be created when a class is defined by placing their
names immediately after the closing brace, as we do in structures.
For example, let’s say we have a class Car which has data members
(variables) such as speed, weight, price and functions such as
gearChange(), slowDown(), brake() etc. Now let’s say I create a object of
this class named FordFigo which uses these data members and functions
and give them its own values. Similarly we can create as many objects as
we want using the blueprint (class).
class Car
{
//Data members
char name[20];
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14

Partial preview of the text

Download C++ Programming – Chapter: Classes & Objects | Complete Diploma IT Notes with Programs and more Study notes Object Oriented Programming in PDF only on Docsity!

Chapter 02. Classes & Objects

Class

Class is a way to bind data and its associated functions together. Class can also be defined as user defined data type that contains data members and member functions in it. So, class is a blueprint for object. That is, it defines what an object of the class will consist of and what operations can be performed on such an object.

Specifying a Class

Generally, a class specification has two parts:

  1. Class declaration
  2. Class function definitions

Class declaration syntax:

class class_name { private: variable declarations; function declarations; public: variable declarations; function declarations; };

Objects

Objects are the basic unit of OOP. They are instances of class, in which data members and various member functions that operate on data are bundled as a unit called as object.

Creating Objects

Once a class is declared, we can create variables of that type by using the class name, like any other built-in type variable.

Objects can also be created when a class is defined by placing their names immediately after the closing brace, as we do in structures.

For example, let’s say we have a class Car which has data members (variables) such as speed, weight, price and functions such as gearChange(), slowDown(), brake() etc. Now let’s say I create a object of this class named FordFigo which uses these data members and functions and give them its own values. Similarly we can create as many objects as we want using the blueprint (class).

class Car

{

//Data members char name[20];

int speed; int weight;

public: //Functions void brake(){ } void slowDown(){ }

};

int main()

{ //ford is an object Car ford;

}

Access Specifiers

Access specifiers in C++ class defines the access control rules. C++ has 3 new keywords introduced, namely,

  1. public
  2. private
  3. protected

These access specifiers are used to set boundaries for availability of members of class be it data members or member functions. Access specifiers in the program, are followed by a colon. You can use one, two or all 3 specifiers in the same class to set different boundaries for different class members.

Public

Public, means all the class members declared under public will be

available to everyone. The data members and member functions declared public can be accessed by other classes too. That means, public members

can be accessed from outside the class also.

class PublicAccess {

public: // public access specifier int x; // Data Member Declaration

int getVolume() { return sidesideside; //returns volume of cube } };

Outside the class definition

But if we plan to define the member function outside the class definition then we must declare the function inside class definition and then define it outside. And if its defined outside the class, then we have to use the scope resolution :: operator along with class name along with function name.

Example :

class Cube

{

public: int side; int getVolume(); }

int Cube :: getVolume() // defined outside class definition

{ return sidesideside;

}

The main function for both the function definition will be same. Inside main() we will create object of class, and will call the member function using dot. operator. int main()

{

Cube C1; C1.side=4; // setting side value cout<< "Volume of cube C1 ="<< C1.getVolume();

}

Memory allocations for objects

Once you define class it will not allocate memory space for the data member of the class. data member of the class can contain different value for the different object thus memory allocation is performed separately for each data member for different object at the time of creating an object. Member function remains common for all objects. Memory allocation is done only once for member function at the time of defining it. The memory allocation of class members is shown below:

Static data members

It is a variable which is declared with the static keyword, it is also known

as class member, thus only single copy of the variable creates for all

objects.

Characteristics of static member variable are:

  1. It is initialized to zero when the first object of the class is created. No other initialization is permitted.
  2. Static elements are allocated storage only once in a program lifetime in static storage area.
  3. It is visible only within the class, but its scope is entire program lifetime.

Static members are normally used to maintain values common to the entire class.

Any changes in the static data member through one member function will

reflect in all other object’s member functions.

Declaration

static data_type member_name;

Defining the static data member

It should be defined outside of the class following this syntax:

data_type class_name :: member_name =value;

Member Function 1 Member Function 2

Common to all Objects

Member

Variable 2

Member

Variable 1

Object 2

Member

Variable 2

Member

Variable 1

Object 1

Member

Variable 1

Member

Variable 2

Object 3

Memory allocated when objects are created

public: static int ABC; };

//defining int Demo :: ABC =10;

int main() {

cout<<"\nValue of ABC: "<

class Demo { private: //static data members static int X; static int Y;

public: //static member function static void Print() { cout <<"Value of X: " << X << endl;

cout <<"Value of Y: " << Y << endl; } };

//static data members initializations int Demo :: X =10; int Demo :: Y =20;

int main() { Demo OB; //accessing class name with object name cout<<"Printing through object name:"< method1(); method2();

methodN(); };

class-name obj[ size ];

Example for Array of object

#include #include

class Employee { int Id; char Name[25]; int Age; long Salary;

public: void GetData() //Statement 1 : Defining GetData() { cout<<"\n\tEnter Employee Id : "; cin>>Id;

cout<<"\n\tEnter Employee Name : "; cin>>Name;

cout<<"\n\tEnter Employee Age : "; cin>>Age;

cout<<"\n\tEnter Employee Salary : "; cin>>Salary; }

void PutData() //Statement 2 : Defining PutData() {

cout<<"\n"< void main() {

int i;

Employee E[3]; //Statement 3 : Creating Array of 3 Employees

for(i=0;i<3;i++) { cout<<"\nEnter details of "< return 0; } Output

Value of A : 10 Value of A : 20 Value of A : 30

Concepts of Constructors

Constructor is a special function used to initialize class data members or we can say constructor is used to initialize the object of class.

Characteristics constructor.

  • Constructor name class name must be same.
  • Constructor doesn't return value.
  • Constructor is invoked automatically, when the object of class is created.

Types of Constructor

  • Default Constructor
  • Parameterize Constructor

Default Constructor Construct without parameter is called default constructor.

Example of C++ default constructor

#include #include class Student { int Roll; char Name[25]; float Marks; public: Student() //Default Constructor { Roll = 1; strcpy(Name,"Kumar"); Marks = 78.42; } void Display() { cout<<"\n\tRoll : "< void main() {

Student S; //Creating Object S.Display(); //Displaying Student Details

}

Output :

Roll : 1 Name : Kumar Marks : 78.

Parameterize Constructor Constructor with parameter is called parameterize constructor.

Example of C++ parameterize constructor

#include #include #include

class Student {

int Roll; char Name[25]; float Marks;

public:

Student(int r,char nm[],float m) //Parameterize Constructor { Roll = r; strcpy(Name,nm); Marks = m; }

void Display() { cout<<"\n\tRoll : "< void Display() { cout<<"\n\tRoll : "< #include

class Example {

int a, b; public:

Example() { a = 50; b = 100; cout << "\nIn Constructor"; }

Example(int x, int y) { a = x; b = y; cout << "\nIn Constructor"; }

void Display() { cout << "\nValues :" << a << "\t" << b; } };

int main() { Example Object(10, 20); Example Object2; Object.Display(); Object2.Display(); getch(); return 0; }

Sample Output Im Constructor Im Constructor Values :10 20 Values :50 100

Constructors with default arguments

#include

class Demo { private: int X,Y; public

Demo()

Destructor Called

Destructor Called

Destructors

Constructor allocates the memory for an object.

Destructor deallocates the memory occupied by an object. Like

constructor, destructor name and class name must be same, preceded by

a tilde(~) sign. Destructor take no argument and have no return value.

Constructor is invoked automatically when the object created.

Destructor is invoked when the object goes out of scope. In other words,

Destructor is invoked, when compiler comes out form the function where

an object is created.

Example of C++ destructor

#include #include #include

class Student {

int Roll; char Name[25]; float Marks;

public:

Student() //Default Constructor { Roll = 4; strcpy(Name,"Sumit"); Marks = 84.56; }

void Display() { cout<<"\n\tRoll : "< ~Student() //Destructor { cout<<"\n\tEnd of program."; }

void main()

{

Student S;

S.Display();

Output :

Roll : 4

Name : Sumit Marks : 89.

End of program.