C++ Classes and Objects

C++ Classes and Objects

Classes and objects are foundational concepts in object-oriented programming (OOP) and C++.

C++ Classes:

A class in C++ is a user-defined data type, similar to struct, but with the capability to contain functions as well. A class is like a blueprint for objects.

Basic Syntax:

class ClassName { access_specifier: // data members // member functions }; 

C++ Objects:

Objects are instances of a class. When you define a class, no memory is allocated. Memory is allocated only when objects of the class are created.

Creating a Simple Class and Object:

1. Defining a Class:

Let's define a simple class named Car.

class Car { public: // Data members (attributes) std::string brand; std::string model; int year; // Member function (behavior) void display() { std::cout << year << " " << brand << " " << model << std::endl; } }; 

2. Creating Objects:

Now, let's create objects of the Car class.

Car car1, car2; 

3. Accessing Attributes and Methods:

Using the dot operator (.), you can access the attributes and methods of a class.

car1.brand = "Toyota"; car1.model = "Corolla"; car1.year = 2020; car2.brand = "Honda"; car2.model = "Civic"; car2.year = 2021; car1.display(); car2.display(); 

Constructors:

A class constructor is a special member function of a class that is executed whenever we create new objects of that class. It has the same name as the class.

class Car { public: std::string brand; std::string model; int year; // Constructor with parameters Car(std::string aBrand, std::string aModel, int aYear) { brand = aBrand; model = aModel; year = aYear; } void display() { std::cout << year << " " << brand << " " << model << std::endl; } }; // Creating objects using constructor Car car1("Toyota", "Corolla", 2020); Car car2("Honda", "Civic", 2021); 

Encapsulation:

One of the primary tenets of OOP, encapsulation is the bundling of data and methods that operate on that data within a single unit, or class. Encapsulation helps in data hiding and exposing only the necessary functionalities.

You achieve encapsulation in C++ using access specifiers like public, private, and protected.

class Circle { private: double radius; public: Circle(double r) : radius(r) { } double area() { return 3.14159 * radius * radius; } }; Circle c(5); std::cout << "Area: " << c.area() << std::endl; 

In the above example, the radius is encapsulated within the Circle class and can't be directly accessed or modified from outside the class.

Conclusion:

Classes and objects are the building blocks of object-oriented programming in C++. Through them, we can implement key OOP concepts like encapsulation, inheritance, and polymorphism. Learning to effectively design and use classes is essential for mastering C++.


More Tags

jsdoc pygame-tick kubernetes-secrets kendo-grid smoothing sublimetext ecmascript-temporal rake-task appsettings android-bottomappbar

More Programming Guides

Other Guides

More Programming Examples