In C++, classes and objects are fundamental concepts used for creating user-defined data types. They provide a blueprint for creating objects, which are instances of a class.
A class acts as a blueprint or template that defines the properties (data) and behaviors (functions) of objects. Imagine a cookie cutter for creating cookies. The cutter (class) defines the overall shape (properties) of the cookie, but each cookie (object) can have its own unique details like frosting or sprinkles.
Classes are composed of members, which can be:
Data Members (Member Variables): These variables store information specific to an object. They represent the object’s properties or state.
Member Functions: These functions define the actions or behaviors that objects of the class can perform.
class Car {
public:
std::string color; // Data member (car's color)
int year; // Data member (car's model year)
void startEngine() { // Member function (starts the engine)
std::cout << "Engine started!" << std::endl;
}
};
Once you have a class definition (the blueprint), you can create objects (instances) of that class. Think of using the cookie cutter to create individual cookies from the dough.
Car myCar; // Declares an object named myCar of class Car
myCar.color = "Red"; // Assigning value to a data member (car color)
myCar.year = 2024; // Assigning value to a data member (car year)
myCar.startEngine(); // Calling a member function on the object
Once you have a class definition (the blueprint), you can create objects (instances) of that class. Think of using the cookie cutter to create individual cookies from the dough.
std::cout << "Car Color: " << myCar.color << std::endl;
std::cout << "Car Year: " << myCar.year << std::endl;
Let’s see how to declare a class and create objects in C++.
#include
#include
using namespace std;
// Defining a class
class Car {
public:
// Data members
string brand;
int year;
// Member function
void display() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}
};
int main() {
// Creating objects of class Car
Car car1, car2;
// Assigning values to members
car1.brand = "Toyota";
car1.year = 2020;
car2.brand = "Honda";
car2.year = 2019;
// Displaying object details
car1.display();
car2.display();
return 0;
}
// output //
Brand: Toyota, Year: 2020
Brand: Honda, Year: 2019
Car
with data members brand
and year
, and a member function display
.main
function, we created two objects car1
and car2
of type Car
.display
function for each object to print their details.public
, private
, and protected
) to control access to members within a class and its derived classes (covered later).
#include
#include
using namespace std;
class MyClass {
public:
int publicVar;
// Constructor
MyClass(int pv) {
publicVar = pv;
}
// Public member function
void publicFunction() {
cout << "Inside public function" << endl;
}
private:
int privateVar;
// Private member function
void privateFunction() {
cout << "Inside private function" << endl;
}
protected:
int protectedVar;
// Protected member function
void protectedFunction() {
cout << "Inside protected function" << endl;
}
public:
// Friend function declaration
friend void friendFunction(MyClass obj);
};
// Friend function definition
void friendFunction(MyClass obj) {
cout << "Accessing private member from friend function: " << obj.privateVar << endl;
cout << "Accessing protected member from friend function: " << obj.protectedVar << endl;
}
int main() {
MyClass obj(10);
// Accessing public member
cout << "Public member: " << obj.publicVar << endl;
obj.publicFunction();
// Private and protected members cannot be accessed directly from outside the class
// cout << "Private member: " << obj.privateVar << endl; // Compilation error
// obj.privateFunction(); // Compilation error
// cout << "Protected member: " << obj.protectedVar << endl; // Compilation error
// obj.protectedFunction(); // Compilation error
// Accessing private and protected members through friend function
friendFunction(obj);
return 0;
}
// output //
Public member: 10
Inside public function
Accessing private member from friend function: 0
Accessing protected member from friend function: 0
MyClass
with public, private, and protected members along with corresponding member functions.main()
function, we create an object obj
of type MyClass
and initialize it with a value.publicVar
and publicFunction()
directly from the main()
function.privateVar
, privateFunction()
, protectedVar
, and protectedFunction()
from the main()
function results in compilation errors.friendFunction()
, which has access to private and protected members of the class.friendFunction()
is declared and defined outside the class and provided access to private and protected members of MyClass
.The protected
access specifier in C++ provides a middle ground between public
and private
. Members declared as protected
within a class are accessible to the class itself, its derived classes, and friend classes.
Protected members can be accessed by member functions of the same class just like private members.
class MyClass {
protected:
int protectedVar;
public:
void accessProtected() {
protectedVar = 10; // Accessing protected member within the class
}
};
Derived classes have access to protected members of their base class. This allows derived classes to inherit and use these members.
class DerivedClass : public MyClass {
public:
void accessProtectedFromDerived() {
protectedVar = 20; // Accessing protected member from derived class
}
};
Friend classes can access protected members of the class if they are declared as friends.
class FriendClass {
public:
void accessProtectedFromFriend(MyClass obj) {
obj.protectedVar = 30; // Accessing protected member from friend class
}
};
#include
using namespace std;
class MyClass {
protected:
int protectedVar;
public:
MyClass() {
protectedVar = 0;
}
void accessProtected() {
protectedVar = 10; // Accessing protected member within the class
}
};
class DerivedClass : public MyClass {
public:
void accessProtectedFromDerived() {
protectedVar = 20; // Accessing protected member from derived class
}
};
class FriendClass {
public:
void accessProtectedFromFriend(MyClass obj) {
obj.protectedVar = 30; // Accessing protected member from friend class
}
};
int main() {
MyClass obj;
DerivedClass derivedObj;
FriendClass friendObj;
obj.accessProtected(); // Accessing protected member within the class
derivedObj.accessProtectedFromDerived(); // Accessing protected member from derived class
friendObj.accessProtectedFromFriend(obj); // Accessing protected member from friend class
cout << "Value of protectedVar: " << obj.protectedVar << endl; // Output: 30
return 0;
}
// output //
Value of protectedVar: 30
MyClass
with a protected member protectedVar
.MyClass
constructor initializes protectedVar
to 0, and accessProtected()
function modifies its value.DerivedClass
is derived from MyClass
and has access to the protected member protectedVar
.FriendClass
is a friend class of MyClass
and can access protectedVar
.main()
function, we create objects of MyClass
, DerivedClass
, and FriendClass
.protectedVar
from within MyClass
, DerivedClass
, and FriendClass
.protectedVar
to verify the changes made by the friend class.Member functions are functions declared within a class and can access the class’s private and protected members.
#include
using namespace std;
// Defining a class with member functions
class Rectangle {
private:
int length;
int width;
public:
void setDimensions(int l, int w) {
length = l;
width = w;
}
int calculateArea() {
return length * width;
}
};
int main() {
Rectangle rect;
// Setting dimensions of the rectangle
rect.setDimensions(5, 10);
// Calculating and printing area
cout << "Area of the rectangle: " << rect.calculateArea() << endl;
return 0;
}
// output //
Area of the rectangle: 50
Rectangle
with private data members length
and width
, and two member functions setDimensions
and calculateArea
.main
function, we created an object rect
of type Rectangle
.setDimensions
function to set the dimensions of the rectangle.calculateArea
function to calculate and print the area of the rectangle.Constructors are special member functions that are automatically called when an object is created. Destructors are called when an object is destroyed.
A default constructor is a constructor that is automatically called when an object is created without any arguments. If no constructor is defined explicitly, the compiler provides a default constructor.
Note – A default constructor is a constructor that takes no arguments.
#include
#include
using namespace std;
class Person {
private:
string name;
int age;
public:
// Default Constructor
Person() {
name = "Unknown";
age = 0;
}
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() {
// Creating an object using the default constructor
Person person;
// Displaying object details
person.display();
return 0;
}
// output //
Name: Unknown, Age: 0
Person
with private data members name
and age
.Person()
which initializes the name
with “Unknown” and age
with 0.main
function, we created an object person
of type Person
using the default constructor.display
function to print the details of the person object.A parameterized constructor is a constructor that takes parameters to initialize the object with specific values.
Note – A parameterized constructor is a constructor that takes one or more parameters.
#include
#include
using namespace std;
class Person {
private:
string name;
int age;
public:
// Parameterized Constructor
Person(string n, int a) {
name = n;
age = a;
}
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() {
// Creating an object using the parameterized constructor
Person person("Alice", 25);
// Displaying object details
person.display();
return 0;
}
// output //
Name: Alice, Age: 25
Person
with private data members name
and age
.Person(string n, int a)
which takes a name and an age to initialize the object.main
function, we created an object person
of type Person
using the parameterized constructor and passed values “Alice” and 25.display
function to print the details of the person object.A copy constructor is a constructor that initializes an object by copying the values of another object of the same class.
Note – A copy constructor is a constructor that takes a reference to an object of the same class and initializes a new object with the same values.
#include
#include
using namespace std;
class Person {
private:
string name;
int age;
public:
// Parameterized Constructor
Person(string n, int a) {
name = n;
age = a;
}
// Copy Constructor
Person(const Person &p) {
name = p.name;
age = p.age;
}
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() {
// Creating an object using the parameterized constructor
Person person1("Alice", 25);
// Creating another object using the copy constructor
Person person2 = person1;
// Displaying object details
person1.display();
person2.display();
return 0;
}
// output //
Name: Alice, Age: 25
Name: Alice, Age: 25
Person
with private data members name
and age
.Person(string n, int a)
to initialize the object with a name and an age.Person(const Person &p)
which takes a reference to another Person
object and copies its values.main
function, we created an object person1
using the parameterized constructor.person2
using the copy constructor and passed person1
as an argument.Person
with private data members name
and age
.Person(string n, int a)
to initialize the object with a name and an age.Person(const Person &p)
which takes a reference to another Person
object and copies its values.main
function, we created an object person1
using the parameterized constructor.person2
using the copy constructor and passed person1
as an argument.
#include
#include
using namespace std;
// Defining a class with constructor and destructor
class Book {
private:
string title;
string author;
public:
// Parameterized Constructor
Book(string t, string a) {
title = t;
author = a;
cout << "Book object created" << endl;
}
// Destructor
~Book() {
cout << "Book object destroyed" << endl;
}
void display() {
cout << "Title: " << title << ", Author: " << author << endl;
}
};
int main() {
// Creating an object of class Book
Book book("The Great Gatsby", "F. Scott Fitzgerald");
// Calling the display function
book.display();
return 0;
}
// output //
Book object created
Title: The Great Gatsby, Author: F. Scott Fitzgerald
Book object destroyed
Book
with private data members title
and author
, a parameterized constructor, a destructor, and a member function display
.main
function, we created an object book
of type Book
by passing values to the constructor.display
function prints the details of the book.public
, private
, protected
) control member visibility within a class and its derived classes.Classes and objects in C++ provide a powerful mechanism for organizing and manipulating data. By encapsulating data and functions into classes, we can build modular and reusable code. Understanding these concepts is essential for writing efficient and maintainable C++ programs. Keep practicing and experimenting to master classes and objects in C++. Happy coding !❤️