C++ classes
Created By: chatGPT
C++ classes are blueprints for creating objects. They encapsulate data and functions that operate on that data. By using classes, you can effectively harness the power of Object-Oriented Programming (OOP), which promotes higher code reusability, scalability, and maintainability.
// Example of a simple C++ class
class Dog {
private:
std::string name;
int age;
public:
// Constructor
Dog(std::string n, int a) : name(n), age(a) {}
// Method to display dog info
void displayInfo() {
std::cout << "Name: " << name << "\n";
std::cout << "Age: " << age << " years\n";
}
};
To create an object of the class, you can use the following syntax. This will allow us to instantiate an object of the Dog class and call its methods.
// Creating an object of Dog class
dog myDog("Buddy", 3);
myDog.displayInfo();
C++ also allows for access modifiers which define the visibility of class members. There are three main access specifiers: public, private, and protected.
// Example of access specifiers
class Car {
private:
std::string model;
public:
int year;
Car(std::string m, int y) : model(m), year(y) {}
void displayModel() {
std::cout << "Model: " << model << "\n";
}
};
In the example above, model is a private member which can only be accessed by methods of the
Car
class, whereas year is a public member and can be accessed from outside the class.// Accessing public and private members
Car myCar("Tesla", 2021);
myCar.year = 2022; // Allowed
// myCar.model = "Tesla X"; // Not allowed - compilation error
myCar.displayModel();
Classes can also inherit from other classes through inheritance. This allows a derived class to inherit attributes and methods from a base class, promoting code reuse.
// Base class
class Animal {
public:
void eat() {
std::cout << "Eating...\n";
}
};
// Derived class
class Cat : public Animal {
public:
void meow() {
std::cout << "Meow!\n";
}
};
Inheritance allows the
Cat
class to inherit the eat
method from the Animal
class. You can create an object of the Cat
class and call both the inherited and its own methods.// Using inherited methods
Cat myCat;
myCat.eat(); // Inherited method
myCat.meow(); // Cat's own method
In conclusion, understanding classes in C++ empowers you to write more organized and manageable code. Embracing OOP principles like encapsulation, inheritance, and polymorphism will greatly enhance your programming skills.
// Final note on OOP principles
// Encapsulation: Bundling data and methods
// Inheritance: Deriving new classes from existing ones
// Polymorphism: Allowing methods to do different things based on the object