C++ OOP Concepts Tutorial

Object-Oriented Programming (OOP) in C++ is a programming paradigm based on objects and classes. This tutorial explores OOP concepts, their importance, and implementation in C++.

1. Classes and Objects

A class is a blueprint for creating objects. Objects are instances of classes.


#include <iostream>
using namespace std;

class Car {
public:
    string brand;
    int year;

    void display() {
        cout << brand << " was made in " << year << endl;
    }
};

int main() {
    Car car1;
    car1.brand = "Toyota";
    car1.year = 2020;
    car1.display();

    return 0;
}
                

2. Encapsulation

Encapsulation restricts direct access to data. It uses access specifiers (private, protected, public).


class Person {
private:
    string name;

public:
    void setName(string n) {
        name = n;
    }

    string getName() {
        return name;
    }
};
                

3. Inheritance

Inheritance allows a class to inherit properties and methods from another class.


class Animal {
public:
    void sound() {
        cout << "Animals make sounds." << endl;
    }
};

class Dog : public Animal {
};

int main() {
    Dog dog1;
    dog1.sound();
    return 0;
}
                

4. Polymorphism

Polymorphism allows the same method to perform different behaviors. Achieved via function overloading and overriding.


class Shape {
public:
    virtual void draw() {
        cout << "Drawing shape" << endl;
    }
};

class Circle : public Shape {
public:
    void draw() override {
        cout << "Drawing circle" << endl;
    }
};

int main() {
    Shape* shape1 = new Circle();
    shape1->draw();
    delete shape1;
    return 0;
}
                

5. Abstraction

Abstraction hides implementation details and shows only essential features.


class AbstractShape {
public:
    virtual void area() = 0; // Pure virtual function
};

class Rectangle : public AbstractShape {
public:
    void area() override {
        cout << "Calculating area of rectangle." << endl;
    }
};
                
0 Interaction
1.5K Views
Views
15 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home