Object-Oriented Programming: Learn about the basic principles of object-oriented programming in C++, including classes, objects, constructors, destructors, access specifiers, inheritance, and polymorphism.

  1. Classes and Objects: A class is a blueprint for creating objects, which are a specific instance of a class. Classes define attributes and methods that an object can have.
1 class Car {
2 public:
3 int speed;
4 void setSpeed(int s) {
5 speed = s;
6 }
7};
8
9int main() {
10 Car carObj;
11 carObj.setSpeed(100);
12 cout << carObj.speed << endl;
13 return 0;
14}
  1. Constructors and Destructors: Constructors are special methods that are executed when an object is created. Destructors are methods that are executed when an object is destroyed.
1 class Car {
2 public:
3 Car() { // default constructor
4 cout << "Car object created" << endl;
5 }
6
7 ~Car() { // destructor
8 cout << "Car object destroyed" << endl;
9 }
10};
11
12int main() {
13 Car carObj;
14 return 0;
15}
  1. Access Specifiers: Access specifiers control the accessibility of class members from outside the class. public members can be accessed anywhere, private members can only be accessed within the class, and protected members can be accessed within the class and its derived classes.
1 class Car {
2 public:
3
int speed;
4 void setSpeed(int s) {
5 speed = s;
6 }
7
8 private:
9 int gear;
10
11 protected:
12 void setGear(int g) {
13 gear = g;
14 }
15};
  1. Inheritance: Inheritance allows one class to inherit attributes and methods from another class. It supports the concept of hierarchical classification.
1class Vehicle {
2 public:
3 void startEngine() {
4 cout << "Engine started" << endl;
5 }
6};
7
8class Car : public Vehicle {
9 public:
10 void setSpeed(int s) {
11 speed = s;
12 cout << "Speed set to " << speed << endl;
13 }
14
15 private:
16 int speed;
17};
18
19int main() {
20 Car carObj;
21 carObj.startEngine();
22 carObj.setSpeed(100);
23 return 0;
24 }
  1. Polymorphism: Polymorphism allows methods to be used with different types of arguments. In C++, we can achieve this using function overloading and operator overloading.
1 class Animal {
2 public:
3 void makeSound() {
4 cout << "The animal makes a sound" << endl;
5 }
6};
7
8class Dog : public Animal {
9 public:
10 void makeSound() {
11 cout << "The dog barks" << endl;
12 }
13};
14
15 int main() {
16 Animal *animal = new Animal();
17 Animal *dog = new Dog();
18
19 animal->makeSound(); // The animal makes a sound
20 dog->makeSound(); // The dog barks
21
22 return 0;
23}

By studying these concepts, you will gain a strong foundation in object-oriented programming in C++.

About Author


Discover more from SURFCLOUD TECHNOLOGY

Subscribe to get the latest posts sent to your email.

Leave a Reply

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

Discover more from SURFCLOUD TECHNOLOGY

Subscribe now to keep reading and get access to the full archive.

Continue reading