36
+t C++Classesand Objects C++Polymorphism C++ Inheritance C++ Abstraction C++ Encapsulation C++
C++ Classes and Objects
Last Updated : 15 Jul, 2024
In C++, classes and objects are the basic building block that leads to Object-
Oriented programming in C++. In this article, we will learn about C++ classes,
objects, look at how they work and how to implement them in our C++
program
[a class is a user-defined data type, which holds its own data members and
member functions, which can be accessed and used by creating an instance
of that class. A C++ class is like a blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with
different names and brands but all of them will share some common properties
like all of them will have 4 wheels, Speed Limit, Mileage range, etc. So here,
the Car is the class, and wheels, speed limits, and mileage are their properties.
vt A Class is a user-defined data type that has data members and member
functions.
Y Data members are the data variables and member functions are the
functions used to manipulate these variables together, these data members
and member functions define the properties and behaviour of the objects in
a Class,
\ In the above example of class Car, the data member will be speed limit,
mileage, etc, and member functions can be applying brakes, increasing
speed, etc.
~/ but we cannot use the class as itis. We first have to create an object of the
class to use its features. An Object is an instance of a Class.
Note: When a class is defined, no memory is allocated but when it isinstantiated (i.e. an object is created) memory is allocated.
A class is defined in C++ using the keyword class followed by the name of the
class. The following is the syntax:
class ClassName {
access_specifier:
// Body of the class
4
Here, the access specifier defines the level of access to the class's data
members.
Example -
class ThisClass {
public:
int var; // data menber
void print() { // menber method
cout << "Hello";
+
4
keyword user-defined name
{ Access specifier: H/can be private public or protected
Data members; // Variables to be used
Member Functions() {} //Methods to access data members
h // Class name ends with a semicolonCwhen 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 to Create an Object
——_
We can create an object of the given class in the same way we declare the
variables of any other inbuilt data type.
ClassName ObjectName;
Example
MyClass obj;
In the above statement, the object of MyClass with name obj is created.
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()
The below program shows how to define a simple class and how to create an
object of it.
cH
a
// C++ progran to iLtustrate how create a simple class and
// object
G — ¥include
include
>
using namespace std;
G 7 vefine a class named ‘Person‘
class Person {public
// bata menbers
string nane;
int age;
// Wenber function to introduce the person
void introduce()
{
cout << "Hi, my name is " << name << * and I am
<< age <<" years old." << endl;
int main()
// Create an object of the Person class
Person persont;
// accessing data members
personlsnane = "Alice";
personl,age = 303
// Call the introduce member method
personl.introduce();
return 0;
Output
Hi, my name is Alice and I am 3@ years old.
—————————————
In C++ classes, we can control the access to the members of the class using
‘Access Specifiers. Also known as access modifier, they are the keywords that
are specified in the class and all the members of the class under that access
specifier will have particular access level.
In C++, there are 3 access specifiers that are as follows:
1, Public: Members declared as public can be accessed from outside the class.
2. Private: Members declared as private can only be accessed within the class
itself.
3. Protected: Members declared as protected can be accessed within the class
and by derived classes.If we do not specify the access specifier, the private specifier is applied to every
member by default.
Example of Access Specifiers
CH
o
// C+ program to demonstrate accessing of data members
Winclude
P using namespace std;
class Geeks {
D private:
string geekrane;
// Access specifier
G pubtic:
71 Member Functions()
void setNane(string name) { geeknane = name; }
void printrane() { cout << "Geeknane is:" << geeknare; }
%
int main()
{
// declare an object of class geeks
Geeks obj15
// accessing data menber
// cannot do it Like: obj1.geekname = "Abhi";
obji.setNene("Abhi");
// accessing menber function
cbj1.printname() ;
return 0;
}
Output
Geekname is:Abhi
In the above example, we cannot access the data member geekname outside
the class. If we try to access it in the main function using dot operator,
obj1.geekname, then program will throw an error.
There are 2 ways to define a member function:
* Inside class definition
* Outside class definitionTill now, we have defined the member function inside the class, but we can
also define the member function outside the class. To define a member
function outside the class definition,
* We have to first declare the function prototype in the class definition.
* Then we have to use the scope resolution:: operator along with the class
name and function name.
Example
cH
© // C++ program to demonstrate member function
// definition outside class
PF Hinclude
using namespace std;
class Geeks {
> public:
string geekname;
G int id;
// printname is not defined inside class definition
void printnane();
// printid is defined inside class definition
void printid() { cout << "Geek id is: " << ids }
// definition of printname using scope resolution operator
cout << “Geekname is: " << geeknane;
}
int main()
t
Geeks ob91;
obj. geeknare
objid = 15;
xy2"5
// call printname()
obj. printname();
cout << endl;
// call printid()
obj1.printic();
return 0;Output
Geekname is
Geek id is:
xyz
15
Note that all the member functions defined inside the class definition are by
default inline, but you can also make any non-class function inline by using the
keyword inline with them. Inline functions are actual functions, which are
copied everywhere during compilation, like pre-processor macro, so the
overhead of function calls is reduced.
Note: Declaring a friend function is a way to give private access to a non-
member function.
Constructors
Constructors are special class members which are called by the compiler every
time an object of that class is instantiated. Constructors have the same name
as the class and may be defined inside or outside the class definition.
There are 4 types of constructors in C++ classes:
* Default Constructors: The constructor that takes no argument is called
default constructor.
* Parameterized Constructors: This type of constructor takes the arguments to
initialize the data members.
* Copy Constructors: Copy constructor creates the object from an already
existing object by copying it.
* Move Constructor: The move constructor also creates the object from an
already existing object but by moving it.
Example of Constructor
cH// C++ program to demonstrate constructors
include
using namespace std;
class Geeks
{
public:
int id;
evrxa@A
//oefault Constructor
Geeks()
{
cout << "Default Constructor called” << endl;
id=-15
+
//Paraneterized Constructor
Geeks(int x)
{
cout <<"Parameterized Constructor called "<< endl;
id-x;
}
ub
int main() {
// objt will call Default Constructor
Geeks obj1;
cout <<"Geek id is: "ccobj1.id << endl;
// 0bj2 will call Parameterized Constructor
Geeks 0b52(21);
cout <<"Geek id is: " <
using namespace std;
class Geeks
{
‘
public:
int ids
//oefinition for Destructor
~Geeks()
{
}
cout << "Destructor called for id
<< id