Loading W Code...
Master Object-Oriented Programming with C++ - powerful features like templates and multiple inheritance.
Learn how to define classes and create objects in C++
A class is a user-defined data type that contains data members and member functions.
An object is an instance of a class.
#include <iostream>
#include <string>
using namespace std;
// Class definition
class Car {
private:
string brand;
string color;
int speed;
public:
// Constructor
Car(string b, string c) {
brand = b;
color = c;
speed = 0;
}
// Member functions
void accelerate() {
speed += 10;
cout << brand << " is now going " << speed << " km/h" << endl;
}
void brake() {
speed = max(0, speed - 10);
cout << brand << " slowed down to " << speed << " km/h" << endl;
}
// Getter
int getSpeed() {
return speed;
}
};
int main() {
// Creating objects
Car myCar("Toyota", "Red");
Car yourCar("Honda", "Blue");
myCar.accelerate(); // Toyota is now going 10 km/h
yourCar.accelerate(); // Honda is now going 10 km/h
return 0;
}
class keyword to define a classpublic, private, protectedData hiding using access specifiers and getters/setters
Encapsulation bundles data and methods together while restricting direct access to internal data.
private: Only accessible within the classprotected: Accessible in class and derived classespublic: Accessible from anywhere#include <iostream>
#include <string>
using namespace std;
class BankAccount {
private:
string accountNumber;
double balance;
public:
// Constructor
BankAccount(string accNum, double initialBalance) {
accountNumber = accNum;
balance = initialBalance;
}
// Getter for balance
double getBalance() const {
return balance;
}
// Getter for account number
string getAccountNumber() const {
return accountNumber;
}
// Controlled deposit
void deposit(double amount) {
if (amount > 0) {
balance += amount;
cout << "Deposited: " << amount << endl;
}
}
// Controlled withdrawal
bool withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
cout << "Withdrawn: " << amount << endl;
return true;
}
cout << "Insufficient funds!" << endl;
return false;
}
};
int main() {
BankAccount account("1234567890", 1000);
cout << "Balance: " << account.getBalance() << endl;
account.deposit(500);
account.withdraw(200);
// account.balance = 0; // Error! balance is private
return 0;
}
Use const after function declaration to indicate it doesn't modify the object.
double getBalance() const { // Won't modify any member
return balance;
}
Create derived classes that inherit from base classes
Inheritance allows a class to inherit properties and methods from another class.
#include <iostream>
#include <string>
using namespace std;
// Base class
class Animal {
protected:
string name;
int age;
public:
Animal(string n, int a) : name(n), age(a) {}
void eat() {
cout << name << " is eating" << endl;
}
void sleep() {
cout << name << " is sleeping" << endl;
}
};
// Derived class
class Dog : public Animal {
private:
string breed;
public:
Dog(string n, int a, string b) : Animal(n, a), breed(b) {}
void bark() {
cout << name << " says: Woof! Woof!" << endl;
}
// Override eat method
void eat() {
cout << name << " the " << breed << " is eating dog food" << endl;
}
};
int main() {
Dog myDog("Buddy", 3, "Golden Retriever");
myDog.eat(); // Overridden
myDog.sleep(); // Inherited
myDog.bark(); // Dog's own
return 0;
}
class Flyable {
public:
void fly() { cout << "Flying!" << endl; }
};
class Swimmable {
public:
void swim() { cout << "Swimming!" << endl; }
};
class Duck : public Flyable, public Swimmable {
public:
void quack() { cout << "Quack!" << endl; }
};
| Base Member | public inheritance | protected | private |
|---|---|---|---|
| public | public | protected | private |
| protected | protected | protected | private |
| private | Not accessible | Not accessible | Not accessible |
Runtime polymorphism with virtual functions and function overloading
class Calculator {
public:
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
};
#include <iostream>
using namespace std;
class Shape {
public:
// Virtual function - can be overridden
virtual void draw() {
cout << "Drawing a shape" << endl;
}
virtual double area() {
return 0;
}
// Virtual destructor (important for polymorphism!)
virtual ~Shape() {}
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
void draw() override {
cout << "Drawing a circle with radius " << radius << endl;
}
double area() override {
return 3.14159 * radius * radius;
}
};
class Rectangle : public Shape {
private:
double width, height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
void draw() override {
cout << "Drawing a rectangle " << width << "x" << height << endl;
}
double area() override {
return width * height;
}
};
int main() {
// Polymorphism with pointers
Shape* shapes[3];
shapes[0] = new Circle(5);
shapes[1] = new Rectangle(4, 6);
shapes[2] = new Circle(3);
for (int i = 0; i < 3; i++) {
shapes[i]->draw(); // Calls correct override
cout << "Area: " << shapes[i]->area() << endl;
delete shapes[i];
}
return 0;
}
virtual keyword in base classoverride keyword in derived class (C++11)virtual, base class method is calledAbstract classes, pure virtual functions, and interfaces
A class with at least one pure virtual function.
#include <iostream>
#include <string>
using namespace std;
// Abstract class
class Vehicle {
protected:
string brand;
public:
Vehicle(string b) : brand(b) {}
// Pure virtual functions (= 0)
virtual void start() = 0;
virtual void stop() = 0;
// Concrete method
void displayBrand() {
cout << "Brand: " << brand << endl;
}
virtual ~Vehicle() {}
};
class Car : public Vehicle {
public:
Car(string b) : Vehicle(b) {}
void start() override {
cout << brand << " car engine started with key" << endl;
}
void stop() override {
cout << brand << " car engine stopped" << endl;
}
};
class ElectricCar : public Vehicle {
public:
ElectricCar(string b) : Vehicle(b) {}
void start() override {
cout << brand << " electric car started silently" << endl;
}
void stop() override {
cout << brand << " electric car powered down" << endl;
}
};
int main() {
// Vehicle v("Generic"); // Error! Can't instantiate abstract class
Vehicle* car1 = new Car("Toyota");
Vehicle* car2 = new ElectricCar("Tesla");
car1->start();
car2->start();
delete car1;
delete car2;
return 0;
}
// Interface - all pure virtual functions
class Printable {
public:
virtual void print() = 0;
virtual ~Printable() {}
};
class Saveable {
public:
virtual void save() = 0;
virtual ~Saveable() {}
};
// Implementing multiple interfaces
class Document : public Printable, public Saveable {
private:
string content;
public:
Document(string c) : content(c) {}
void print() override {
cout << "Printing: " << content << endl;
}
void save() override {
cout << "Saving document..." << endl;
}
};
| Feature | Abstract Class | Interface (Pure Abstract) |
|---|---|---|
| Methods | Can have concrete methods | All pure virtual |
| Data members | Can have data members | Usually no data |
| Constructor | Can have constructor | No constructor |
| Purpose | Partial implementation | Define contract |
Write generic code that works with any data type
#include <iostream>
using namespace std;
// Function template
template <typename T>
T maximum(T a, T b) {
return (a > b) ? a : b;
}
int main() {
cout << maximum(10, 20) << endl; // int
cout << maximum(3.14, 2.71) << endl; // double
cout << maximum('a', 'z') << endl; // char
return 0;
}
template <typename T>
class Stack {
private:
T* arr;
int top;
int capacity;
public:
Stack(int size = 100) {
arr = new T[size];
capacity = size;
top = -1;
}
~Stack() {
delete[] arr;
}
void push(T value) {
if (top < capacity - 1) {
arr[++top] = value;
}
}
T pop() {
if (top >= 0) {
return arr[top--];
}
throw runtime_error("Stack is empty");
}
bool isEmpty() {
return top == -1;
}
};
int main() {
Stack<int> intStack(10);
intStack.push(1);
intStack.push(2);
cout << intStack.pop() << endl; // 2
Stack<string> strStack(10);
strStack.push("Hello");
strStack.push("World");
cout << strStack.pop() << endl; // World
return 0;
}
template <typename K, typename V>
class Pair {
private:
K key;
V value;
public:
Pair(K k, V v) : key(k), value(v) {}
K getKey() { return key; }
V getValue() { return value; }
};
Pair<string, int> age("Alice", 25);
Pair<int, double> score(1, 95.5);