0% found this document useful (0 votes)
19 views14 pages

C++ Classes and Objects Overview

The document provides an overview of classes and objects in C++ programming, detailing the definition and usage of structures, classes, and member functions. It explains concepts such as access specifiers, constructors, destructors, and the creation of objects, including default and parameterized constructors. Additionally, it covers advanced topics like static members, nesting of member functions, and copy constructors.

Uploaded by

yaspatadiya8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views14 pages

C++ Classes and Objects Overview

The document provides an overview of classes and objects in C++ programming, detailing the definition and usage of structures, classes, and member functions. It explains concepts such as access specifiers, constructors, destructors, and the creation of objects, including default and parameterized constructors. Additionally, it covers advanced topics like static members, nesting of member functions, and copy constructors.

Uploaded by

yaspatadiya8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CS -14: C++ and Object Oriented Programming

Unit 2: Classes and Objects, Constructor and Destructor

 C structures revisited

A structure is a collection of variables under a single name. These variables can be of different
types, and each has a name which is used to select it from the structure.

A structure is a convenient way of grouping several pieces of related information together.

Defining a Structure

To define a structure, you must use the struct statement. The struct statement defines a new
data type, with more than one member for your program. The format of the struct statement is
this:

Syntax

struct [structure tag]


{
member definition;
member definition;
...
member definition;
} [one or more structure variables];

Example

struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
} book;

Accessing Structure Members

To access any member of a structure, we use the member access operator (.). The member
access operator is coded as a period between the structure variable name and the structure
member that we wish to access. You would use struct keyword to define variables of structure
type.

struct Books
{
char title[50];
int book_id;
};

Gaurav K Sardhara
MO :- 9067351366 Page | 1
CS -14: C++ and Object Oriented Programming
Unit 2: Classes and Objects, Constructor and Destructor
int main( )
{
Books Book1; /* Declare Book1 of type Book */

/* book 1 specification */
[Link]= "C++ Programming";
Book1.book_id = 6495407;
}

 Specifying a class

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 Definitions:

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.

Classes are defined using either keyword class or keyword struct, with the following syntax:

class class_name
{
access_specifier_1:
member1;
access_specifier_2:
member2;
...
} object_names;

Where class_name is a valid identifier for the class, object_names is an optional list of names
for objects of this class.

The body of the declaration can contain members, which can either be data or function
declarations, and optionally access specifiers.

Gaurav K Sardhara
MO :- 9067351366 Page | 2
CS -14: C++ and Object Oriented Programming
Unit 2: Classes and Objects, Constructor and Destructor
Classes have the same format as plain data structures, except that they can also include
functions and have these new things called access specifiers. Access specifiers are one of the
following three keywords: private, public or protected. These specifiers modify the access rights
for the members that follow them:

The public members:

A public member is accessible from anywhere outside the class but within a program.

The private members:

A private member variable or function cannot be accessed, or even viewed from outside the
class. Only the class and friend functions can access private members.

By default all the members of a class would be private,

The protected members:

A protected member variable or function is very similar to a private member but it provided one
additional benefit that they can be accessed in child classes which are called derived classes.

Example:

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

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.

Gaurav K Sardhara
MO :- 9067351366 Page | 3
CS -14: C++ and Object Oriented Programming
Unit 2: Classes and Objects, Constructor and Destructor

Accessing the Data Members:

The public data members of objects of a class can be accessed using the direct member access
operator (.).

#include <iostream.h>

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

int main( )
{
Box Box1; // Declare Box1 of type Box

// box 1 specification
[Link] = 5.0;
[Link] = 6.0;
[Link] = 7.0;
return 0;

 Defining member functions

A member function of a class is a function that has its definition or its prototype within the class
definition like any other variable.

Member functions can be defined within the class definition or separately using scope resolution
operator, ::. Defining a member function within the class definition declares the function inline,
even if you do not use the inline specifier.

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

double getVolume(void)
{
return length * breadth * height;
}

Gaurav K Sardhara
MO :- 9067351366 Page | 4
CS -14: C++ and Object Oriented Programming
Unit 2: Classes and Objects, Constructor and Destructor
};

If you like you can define same function outside the class using scope resolution operator, :: as
follows:

double Box::getVolume(void)
{
return length * breadth * height;
}

Here, only important point is that you would have to use class name just before :: operator. A
member function will be called using a dot operator (.) on a object where it will manipulate data
related to that object only as follows:

Box myBox; // Create an object

[Link](); // Call member function for the object

 Nesting of Member functions

A member function of a class can be called only by an object of that class using a dot operator.
However, there is an exception to this. A member function can be called by using its name inside
another member function of the same class. This is known as nesting of member functions.

#include<iostream.h>
#include<conio.h>

class emp
{
private:
int id;
char name[20];
public:
void setData();
void printData();
};
void emp::setData()
{
cout<<"Enter emp id :: ";
cin>>id;
cout<<"Enter emp name :: ";
cin>>name;
}
void emp::printData()
{
setData() //nesting of member function

Gaurav K Sardhara
MO :- 9067351366 Page | 5
CS -14: C++ and Object Oriented Programming
Unit 2: Classes and Objects, Constructor and Destructor

cout<<"Employee ID :: "<<id;
cout<<endl<<"Employee Name :: "<<name;

}
int main()
{
clrscr();
emp obj1;
[Link]();
getch();
return 0;
}

 Memory allocation for objects

Gaurav K Sardhara
MO :- 9067351366 Page | 6
CS -14: C++ and Object Oriented Programming
Unit 2: Classes and Objects, Constructor and Destructor

 Arrays of objects
Arrays of variables of type "class" is known as "Array of objects". The "identifier" used to refer
the array of objects is an user defined data type.

syntax

<class_name> <obj_name>[size];
example

emp obj[5];

how to access members

example

obj[0].printData();

 Static variable in C language


Static variables are those variables whose life time remains equal to the life time of the program.

Gaurav K Sardhara
MO :- 9067351366 Page | 7
CS -14: C++ and Object Oriented Programming
Unit 2: Classes and Objects, Constructor and Destructor

 Static data member

 We can define class members static using static keyword.


 When we declare a member of a class as static it means no matter how many objects of
the class are created, there is only one copy of the static member. A static member is
shared by all objects of the class.
 All static data is initialized to zero when the first object is created, if no other initialization
is present.
 We can't put it in the class definition but it can be initialized outside the class as done in
the following example by re-declaring the static variable, using the scope resolution
operator :: to identify which class it belongs to.

syntax:

<data_type> <class_name>::<static_variable_name> [=initial_value]

 Static member functions

 By declaring a function member as static, you make it independent of any particular


object of the class.
 A static member function can be called even if no objects of the class exist and the static
functions are accessed using only the class name and the scope resolution operator ::.
 A static member function can only access static data member, other static member
functions and any other functions from outside the class.
 You could use a static member function to determine whether some objects of the class
have been created or not.

Gaurav K Sardhara
MO :- 9067351366 Page | 8
CS -14: C++ and Object Oriented Programming
Unit 2: Classes and Objects, Constructor and Destructor
Constructors and Destructor

Object Oriented Programming


 Class
 Object
 Inheritance
 Polymorphism
 Encapsulation
 Constructors
 Destructors

 Constructor and Destructor


A class constructor is a special member function of a class that is executed whenever we create
new objects of that class.

A destructor is a special member function of a class that is executed whenever an object of it's
class goes out of scope or whenever the delete expression is applied to a pointer to the object
of that class.

 Characteristics of constructor
 Constructor is special member function that generally use to initialize value of data
member.
 It is special because its name is same as the class name. It invoke whenever object of
class is created.
 A class constructor is a special member function of a class that is executed whenever
we create new objects of that class.
 A constructor will have exact same name as the class and it does not have any return
type at all, not even void. Constructors can be very useful for setting initial values for
certain member variables.
 It should be declared in public section.
 They do not return any value not even void therefore they can not return value
 Constructors and destructors do not have return types and they can return values.
 Constructors cannot be declared with the keyword virtual.
 Constructors and destructors cannot be declared static, const, or volatile.

Syntax

<class_name> <constructor_name>
{
}

Example

#include <iostream.h>

class a

Gaurav K Sardhara
MO :- 9067351366 Page | 9
CS -14: C++ and Object Oriented Programming
Unit 2: Classes and Objects, Constructor and Destructor
{
public:
a(); // This is the constructor
};
// constructor defination
a::a(void)
{
cout << "Object is being created" << endl;
}

int main( )
{
a obj1; //object create and constructor executes
return 0;
}

 Default constructors
 A constructor without any parameters is called as default constructor.
 A default constructor is a constructor that takes no arguments. It is also called a 0-
argument constructor. With a default constructor, you can give initial values to data
members even though the client did not specify them.

 Parameterized Constructor

 A constructor with at least one parameter is called as parameterized constructor.


Advantage of parameterized constructor is you can initialize each instance of the class
to different values.

Example
#include <iostream.h>

class a
{
private:
int no1,no2;
public:
a(int,int); //This is parameterize constructor
};
a::a(int n1,int n2)
{
no1=n1;
no2=n2;
}
int main( )
{
a obj2(10,20) //object create and parameterize constructor executes

Gaurav K Sardhara
MO :- 9067351366 Page | 10
CS -14: C++ and Object Oriented Programming
Unit 2: Classes and Objects, Constructor and Destructor
return 0;
}

 Explicit calling of Constructors


When a constructor has been parameterized we must pass the initial values as arguments to
the constructor function when an object is declared. This can be done in two ways.

by calling the constructor explicitly


by calling the constructor implicitly

example

a obj1 = a(10,20); //explicit call

a obj1(10,20); //implicit call

 Multiple constructor in a class (Constructor Overloading)


A class can have multiple constructors that assign the fields in different ways. Sometimes it's
beneficial to specify every aspect of an object's data by assigning parameters to the fields, but
other times it might be appropriate to define only one or a few.

Constructors Overloading are used to increase the flexibility of a class by having more number
of constructor for a single class. By have more than one way of initializing objects can be done
using overloading constructors.

Compiler differentiates which constructor is to called depending upon number of parameters


and their sequence of data type.

Example

#include <iostream.h>

class a
{
private:
int no1,no2;
public:
a(); // This is the default constructor
a(int,int);
};
// constructor definition
a::a(void)
{
cout << "Object is being created" << endl;
}

Gaurav K Sardhara
MO :- 9067351366 Page | 11
CS -14: C++ and Object Oriented Programming
Unit 2: Classes and Objects, Constructor and Destructor
a::a(int n1,int n2)
{
no1=n1;
no2=n2;
}
int main( )
{
a obj1; //object create and constructor executes (default constructor)
a obj2(10,20) //object create and parameterize constructor executes
return 0;
}

 Constructor with default argument


Example

#include <iostream.h>

class a
{
private:
int no1,no2;
public:
a(int,int n2=20); //second parameter is default for constructor
};
// constructor definition
a::a(int n1,int n2)
{
no1=n1;
no2=n2;
}
int main( )
{
a obj1(10); //object create and constructor executes with default value
a obj2(10,30) //object create and parameterize constructor executes
return 0;
}

 Copy constructor
The copy constructor is special kind of constructors which creates a new object which is copy of
existing class.
The copy constructor receives an object of its own class as argument and allows to create new
object.

The copy constructor is used to:

 Initialize one object from another of the same type.

Gaurav K Sardhara
MO :- 9067351366 Page | 12
CS -14: C++ and Object Oriented Programming
Unit 2: Classes and Objects, Constructor and Destructor
 Copy an object to pass it as an argument to a function.
 Copy an object to return it from a function.

Syntax

Define copy constructor

<class_name> (<class_name> &<obj>)


{
// body of constructor
}

calling copy constructor

<class_name> <obj_name> (<object_name>)

 The Destructors

A destructor is a special member function of a class that is executed whenever an object of its
class goes out of scope or whenever the delete expression is applied to a pointer to the object
of that class.

 A destructor will have exact same name as the class prefixed with a tilde (~).
 It can neither return a value nor can it take any parameters.
 Destructor can be very useful for releasing resources before coming out of the program
like closing files, releasing memories etc.
 The destructor automatically execute when object is destroy.
 Only one destructor may declare in one class. There is no way to overload destructors
because they cannot de differentiated from each other based on signature.

Syntax

Declaration
~<destructor_name)();

Definition
<class_name>::~<destructor_name>)()
{
//statements
}

Gaurav K Sardhara
MO :- 9067351366 Page | 13
CS -14: C++ and Object Oriented Programming
Unit 2: Classes and Objects, Constructor and Destructor

 Dynamic initialization of objects

The dynamic initialization means that the initial values may be provided during run time. Even
class objects can be initialized dynamically. I.e. with the values provided at run time.

One advantage of dynamic initialization is that we can provide various initialization formats
using overloaded constructors.

Example

#include <iostream.h>

class a
{
private:
int no1,no2;
public:

a(int,int); //second parameter is default for constructor


};
// constructor definition
a::a(int n1,int n2)
{
no1=n1;
no2=n2;
}
int main( )
{
int n1,n2;
a obj1,obj2;

cout<<”enter n1 and n2”;


cin>>n1>>n2;
obj1=a(n1,n2);

cout<<”Enter n1 and n2”;


cin>>n1>>n2;
obj2=a(n1,n2);

return 0;
}

Gaurav K Sardhara
MO :- 9067351366 Page | 14

You might also like