C++ Classes and Objects

C++ is an object-oriented programming language, which means that it supports the creation of objects, classes, and their methods and properties. In this article, we will discuss the basics of C++ classes and objects and how they are used in C++ programming.

What are Classes?

A class is a blueprint for creating objects (a particular data structure), providing initial values for state (member variables or attributes), and implementations of behavior (member functions or methods).

For example, in an application that simulates a bank account, the bank account class would have member variables such as account number, account balance, account type, etc. The class would also have member methods such as deposit(), withdraw(), and transfer().

A class definition starts with the keyword “class”, followed by the class name and a set of curly braces that enclose the class body. The class body contains the data members and member functions of the class.

class BankAccount {
public:
    int accountNumber;
    double balance;
    string accountType;

    void deposit(double amount);
    void withdraw(double amount);
    void transfer(double amount, BankAccount &otherAccount);
};

In the above example, the class BankAccount has three data members: accountNumber, balance, and accountType. It also has three member functions: deposit(), withdraw(), and transfer(). The keyword “public” before the colon is called access specifier, which is used to specify the access level of the class members. In this case, all members of the class are public, which means they can be accessed from anywhere in the program.

What are Objects?

An object is an instance of a class. It is created using the class definition and contains its own copy of the data members defined in the class. Objects can also access the member functions of the class to manipulate the data members.

To create an object of a class, we use the class name followed by the object name and the assignment operator (=).

BankAccount account1;

This creates an object called account1 of the class BankAccount. We can access the data members of the object using the dot operator (.).

account1.accountNumber = 12345;
account1.balance = 1000.00;
account1.accountType = "Savings";

We can also call the member functions of the class using the object.

account1.deposit(500.00);
account1.withdraw(200.00);

Constructors and Destructors

A constructor is a special member function that is automatically called when an object of a class is created. It has the same name as the class and does not have a return type. In C++, constructors can be defined with or without parameters.

For example, the following is a constructor for the BankAccount class that initializes the accountNumber and balance properties when an object is created.

class BankAccount {
public:
    int accountNumber;
    double balance;
    string accountType;

BankAccount(int accountNumber, double balance, string accountType) {
    this->accountNumber = accountNumber;
    this->balance = balance;
    this->accountType = accountType;
}

void deposit(double amount);
void withdraw(double amount);
void transfer(double amount, BankAccount &otherAccount);
};

Now, when we create an object of the BankAccount class, we can pass in the account number, balance, and account type as arguments to the constructor.

BankAccount account1(12345, 1000.00, "Savings");

A destructor is a special member function that is automatically called when an object of a class is destroyed. It also has the same name as the class, but is preceded by a tilde (~). It does not have any return type or parameters. The destructor is used to release any resources that were acquired by the object, such as memory or file handles.

class BankAccount {
public:
    int accountNumber;
    double balance;
    string accountType;

BankAccount(int accountNumber, double balance, string accountType) {
    this->accountNumber = accountNumber;
    this->balance = balance;
    this->accountType = accountType;
}

~BankAccount() {
    // code to release resources
}

void deposit(double amount);
void withdraw(double amount);
void transfer(double amount, BankAccount &otherAccount);
};

Inheritance

Inheritance is a feature of object-oriented programming that allows a class to inherit the properties and methods of another class. The class that inherits the properties and methods is called the derived class, and the class from which the properties and methods are inherited is called the base class. Inheritance is represented using the keyword “:”, and is used to create a hierarchy of classes, where a derived class can inherit properties and methods from one or more base classes.

class SavingsAccount : public BankAccount {
public:
    double interestRate;

SavingsAccount(int accountNumber, double balance, string accountType, double interestRate) : BankAccount(accountNumber, balance, accountType) {
    this->interestRate = interestRate;
}

double calculateInterest() {
    return balance * interestRate;
}
};

In the above example, the SavingsAccount class inherits from the BankAccount class, which means it has access to all the properties and methods of the BankAccount class, in addition to its own properties and methods. The SavingsAccount class also has its own constructor, which calls the constructor of the base class using the “: BankAccount(…)”.

Inheritance allows for code reuse and makes it easier to add new features to existing classes. It also allows for the creation of more specialized classes that inherit the properties and methods of more general classes.

Polymorphism

Polymorphism is another feature of object-oriented programming that allows objects of different classes to be treated as objects of a common base class. This means that a single function or operator can be used to operate on objects of different classes. There are two types of polymorphism in C++: compile-time polymorphism and runtime polymorphism.

Compile-time polymorphism, also known as function overloading or operator overloading, occurs when multiple functions or operators have the same name but different parameter lists. The correct function or operator is chosen at compile-time based on the type and number of arguments passed to it.

class Calculator {
public:
    int add(int x, int y) {
        return x + y;
    }

double add(double x, double y) {
    return x + y;
}
};

int main() {
Calculator calculator;
int result1 = calculator.add(1, 2);
double result2 = calculator.add(1.5, 2.5);
return 0;
}

In this example, the add function is overloaded twice, once for integers and once for doubles. When the add function is called with two integers, the first version of the function is called, and when it is called with two doubles, the second version of the function is called. This is an example of compile-time polymorphism.

Runtime polymorphism, also known as virtual functions, occurs when a derived class overrides a virtual function of its base class. The correct function is chosen at runtime based on the actual type of the object, not the type of the pointer or reference used to call the function.

class Shape {
public:
    virtual double area() {
        return 0;
    }
};
class Rectangle : public Shape {
double width, height;
public:
Rectangle(double width, double height) : width(width), height(height) {}
double area() {
return width * height;
}
};

class Circle : public Shape {
double radius;
public:
Circle(double radius) : radius(radius) {}
double area() {
return 3.14 * radius * radius;
}
};

int main() {
Shape *shapes[3];
shapes[0] = new Rectangle(2, 3);
shapes[1] = new Circle(2);
shapes[2] = new Rectangle(4, 5);


for (int i = 0; i < 3; i++) {
    cout << "Area of shape " << i + 1 << " : " << shapes[i]->area() << endl;
}

return 0;
}

In this example, the Shape class has a virtual function area() that returns 0. The Rectangle and Circle classes are derived from Shape, and they override the area() function to return the actual area of the shape. When the area function is called on a Shape pointer or reference, the correct version of the function is called based on the actual type of the object, resulting in runtime polymorphism.

Leave a Reply

Your email address will not be published. Required fields are marked *