CodeToLive

Classes and Objects in C++

Classes and objects are the foundation of object-oriented programming in C++. A class is a blueprint for creating objects, and an object is an instance of a class.

Defining a Class

Classes in C++ are defined using the class keyword. They can contain data members (attributes) and member functions (methods).


#include <iostream>
#include <string>

class Dog {
public:
    std::string name;
    std::string breed;

    Dog(std::string name, std::string breed) {
        this->name = name;
        this->breed = breed;
    }

    void bark() {
        std::cout << "Woof!" << std::endl;
    }
};

int main() {
    Dog myDog("Buddy", "Golden Retriever");
    myDog.bark();  // Output: Woof!
    return 0;
}
      

Access Specifiers

C++ provides three access specifiers: public, private, and protected.


#include <iostream>

class Example {
public:
    int publicVar;  // Accessible from anywhere

private:
    int privateVar; // Accessible only within the class

protected:
    int protectedVar; // Accessible within the class and derived classes
};
      

Encapsulation

Encapsulation is the concept of bundling data and methods that operate on the data within a single unit (class).


#include <iostream>

class BankAccount {
private:
    double balance;

public:
    BankAccount(double initialBalance) : balance(initialBalance) {}

    void deposit(double amount) {
        balance += amount;
    }

    void withdraw(double amount) {
        if (amount <= balance) {
            balance -= amount;
        } else {
            std::cout << "Insufficient funds!" << std::endl;
        }
    }

    double getBalance() {
        return balance;
    }
};

int main() {
    BankAccount account(1000);
    account.deposit(500);
    account.withdraw(200);
    std::cout << "Balance: " << account.getBalance() << std::endl;  // Output: 1300
    return 0;
}
      

Inheritance

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


#include <iostream>

class Animal {
public:
    void speak() {
        std::cout << "Animal sound" << std::endl;
    }
};

class Cat : public Animal {
public:
    void speak() {
        std::cout << "Meow" << std::endl;
    }
};

int main() {
    Cat myCat;
    myCat.speak();  // Output: Meow
    return 0;
}
      

Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common base class.


#include <iostream>

class Animal {
public:
    virtual void speak() {
        std::cout << "Animal sound" << std::endl;
    }
};

class Dog : public Animal {
public:
    void speak() override {
        std::cout << "Woof!" << std::endl;
    }
};

class Cat : public Animal {
public:
    void speak() override {
        std::cout << "Meow" << std::endl;
    }
};

int main() {
    Animal* animals[2];
    animals[0] = new Dog();
    animals[1] = new Cat();

    for (int i = 0; i < 2; i++) {
        animals[i]->speak();  // Output: Woof! Meow
    }

    return 0;
}
      

Constructors and Destructors

Constructors are special methods called when an object is created, and destructors are called when an object is destroyed.


#include <iostream>

class Example {
public:
    Example() {
        std::cout << "Constructor called!" << std::endl;
    }

    ~Example() {
        std::cout << "Destructor called!" << std::endl;
    }
};

int main() {
    Example obj;  // Constructor called
    return 0;     // Destructor called
}
      

Static Members

Static members belong to the class rather than any specific object. They are shared across all instances of the class.


#include <iostream>

class Counter {
public:
    static int count;

    Counter() {
        count++;
    }

    static void displayCount() {
        std::cout << "Count: " << count << std::endl;
    }
};

int Counter::count = 0;

int main() {
    Counter c1, c2, c3;
    Counter::displayCount();  // Output: Count: 3
    return 0;
}
      

Friend Functions and Classes

Friend functions and classes can access private and protected members of a class.


#include <iostream>

class Example {
private:
    int secret = 42;

    friend void revealSecret(Example& obj);
};

void revealSecret(Example& obj) {
    std::cout << "Secret: " << obj.secret << std::endl;
}

int main() {
    Example obj;
    revealSecret(obj);  // Output: Secret: 42
    return 0;
}
      
Back to Tutorial