C++ is an object-oriented programming language, and one of its key features is the ability to create and use classes and objects. Classes and Objects in C++ are the basic building blocks for Object Oriented Programming. In this article, we are going to learn the concept of classes and objects in detail with real-life examples.
What is a Class?
At its core, a class is a blueprint for creating objects. It encapsulates data (attributes) and behaviors (methods), providing a logical structure for organizing and modeling real-world entities.
Data Members (Attributes): Data members define the attributes of a class, representing its state. They can include fundamental types or other user-defined types.(alert-passed)
Member Functions (Methods): Member functions define the behaviors of a class. They encapsulate operations that can be performed on the class's data.(alert-passed)
Syntax: In C++, declaring a class involves using the class keyword, followed by the class name and a set of curly braces containing class members.
class ClassName { Access Specifier: Data Member; Member Function(); };
class Car { public: //Access Specifier // Attributes string brand; string model; int year; bool engineRunning; // Member Function to Start the Engine void startEngine() { if (!engineRunning) { cout << "Starting the engine...\n"; engineRunning = true; } else { cout << "The engine is already running.\n"; } } };
What is an Object?
ClassName objectName; // Creating an object
Access Specifiers in C++.
- Public: Members declared as public are accessible from any part of the program. They have no restrictions on access.
- Private: Members declared as private are only accessible within the same class. They are not accessible from outside the class.
- Protected: Members declared as protected are similar to private members but have one additional feature: they can be accessed in the derived classes. They are not accessible from outside the class.
//Access Specifier Example class AccessExample { public: int publicVar; private: int privateVar; protected: int protectedVar; public: void displayValues() { cout << "Public: " << publicVar << "\n"; cout << "Private: " << privateVar << "\n"; //Err: private is not accessible cout << "Protected: " << protectedVar << "\n"; } };
Constructors.
- A default constructor is a constructor that takes no parameters.
- If a class does not have any constructor defined, the compiler automatically generates a default constructor.
- It initializes the data members with default values (zero or null, depending on the data type).
- A parameterized constructor is a constructor that takes parameters.
- It allows you to initialize the object with specific values when it is created.
#include <iostream> class Car { private: std::string brand; int year; public: // Default Constructor Car() { brand = "Unknown"; year = 0; } // Parameterized Constructor Car(std::string carBrand, int carYear) { brand = carBrand; year = carYear; } void displayInfo() { std::cout << "Brand: " << brand << "\n"; std::cout << "Year: " << year << "\n"; } }; int main() { // Using Default Constructor Car defaultCar; defaultCar.displayInfo(); // Using Parameterized Constructor Car customCar("Toyota", 2022); customCar.displayInfo(); return 0; }
Brand: Unknown
Year: 0
Brand: Toyota
Year: 2022
Destructor.
#include <iostream>
class MyClass { public: // Constructor MyClass() { std::cout << "Constructor called\n"; } // Destructor ~MyClass() { std::cout << "Destructor called\n"; } }; int main() { // Object creation MyClass obj; // Constructor called // Object goes out of scope // Destructor is automatically called here return 0; }
Constructor called Destructor called
- Use access specifiers (public, private, protected) to control the visibility of class members.
- Always define a constructor and, if needed, a destructor to manage the object's lifecycle.
- Ensure that all class members are properly initialized, either through default values, member initialization lists, or in the constructor body.
- Consider making functions const-correct when they do not modify the object's state.
- Access static members using the class name, not an instance.
- Prefer composition over inheritance to achieve polymorphic behavior.
No comments:
Post a Comment