Classes are the cornerstone of Object-Oriented Programming (OOP) in C++. They allow you to encapsulate data and functions, organize your code, and implement concepts like inheritance and polymorphism. This tutorial walks you through the basics of creating and using C++ classes, covering key concepts like public and private access specifiers, and polymorphism.
1. What is a Class?
A class is a blueprint for creating objects. It contains:
- Attributes (data members)
- Methods (functions that operate on the data)
2. Creating a Simple Class
Example: A Basic Class
#include <iostream>
#include <string>
Using namespace std;
class Person {
private:
string name; // Private attribute
int age; // Private attribute
public:
// Constructor
Person(string personName, int personAge) {
name = personName;
age = personAge;
}
// Public method to display information
void displayInfo() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() {
// Create an object of the class
Person person1("Alice", 30);
// Access the public method
person1.displayInfo();
return 0;
}
Key Points:
- Attributes (
nameandage) areprivateto ensure encapsulation. - The constructor initializes the attributes.
- The
displayInfo()method ispublic, allowing external access.
3. Access Specifiers: public and private
private: Members can only be accessed by the class itself.public: Members can be accessed from outside the class.
Example: Access Specifiers
#include <iostream>
class Example {
private:
int privateData;
public:
void setPrivateData(int value) {
privateData = value;
}
int getPrivateData() {
return privateData;
}
};
int main() {
Example obj;
obj.setPrivateData(42); // Accessing private data through a public method
cout << "Private data: " << obj.getPrivateData() << endl;
return 0;
}
4. Inheritance
Inheritance allows a class to inherit attributes and methods from another class.
Example: Inheritance
#include <iostream>
// Base class
class Animal {
public:
void eat() {
cout << "This animal is eating." << endl;
}
};
// Derived class
class Dog : public Animal {
public:
void bark() {
cout << "The dog is barking." << endl;
}
};
int main() {
Dog dog;
dog.eat(); // Inherited method
dog.bark(); // Method of Dog class
return 0;
}
5. Polymorphism
Polymorphism allows a function to behave differently based on the object that calls it. It is typically achieved through virtual functions.
Example: Polymorphism
#include <iostream>
// Base class
class Animal {
public:
virtual void sound() { // Virtual function
cout << "This animal makes a sound." << endl;
}
};
// Derived class
class Dog : public Animal {
public:
void sound() override { // Override base class method
cout << "The dog barks." << endl;
}
};
// Another derived class
class Cat : public Animal {
public:
void sound() override {
cout << "The cat meows." << endl;
}
};
int main() {
Animal* animal; // Pointer to base class
Dog dog;
Cat cat;
animal = &dog;
animal->sound(); // Calls Dog's sound()
animal = &cat;
animal->sound(); // Calls Cat's sound()
return 0;
}
Key Points:
virtualkeyword: Indicates a method can be overridden in a derived class.- Dynamic Dispatch: Determines the appropriate method at runtime.
6. Encapsulation
Encapsulation bundles data and functions together and restricts direct access to some components.
Example: Encapsulation
#include <iostream>
class BankAccount {
private:
double balance;
public:
BankAccount(double initialBalance) {
balance = initialBalance;
}
void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
} else {
cout << "Insufficient funds." << endl;
}
}
double getBalance() {
return balance;
}
};
int main() {
BankAccount account(100.0);
account.deposit(50.0);
account.withdraw(30.0);
cout << "Balance: $" << account.getBalance() << endl;
return 0;
}
7. Summary
public: Allows external access.private: Restricts access to class members.- Inheritance: Enables code reuse and specialization.
- Polymorphism: Allows functions to behave differently based on object type.
- Encapsulation: Protects data and ensures only valid operations are performed.
8. Practice Problems
- Create a
Shapebase class with derived classesCircleandRectangle. Implement polymorphism to calculate the area of each shape. - Write a
Carclass withprivateattributes for brand, model, and year, and public methods to set and get these values. - Create a
Studentclass with aprivateattribute for grades. Implement a method to calculate the average grade.
