C++ Classes and Objects

Classes and objects are fundamental concepts in Object-Oriented Programming (OOP), and C++ is an object-oriented language. In this article, we will explore the basics of C++ classes and objects, including how to declare, define, and use classes and objects in your programs.

Declaring a Class

A class in C++ is a blueprint for creating objects (a particular data structure), providing initial values for state (member variables or attributes), and implementations of behavior (member functions or methods). To declare a class in C++, use the class keyword followed by the class name, followed by the class body enclosed in curly braces. For example, consider the following code:

1class Rectangle { 2 int width, height; 3 public: 4 void setWidth(int w) { 5 width = w; 6 } 7 void setHeight(int h) { 8 height = h; 9 } 10 int getArea() { 11 return width * height; 12 } 13};

In this example, we declare a class Rectangle with two member variables width and height and three member functions setWidth, setHeight, and getArea. The member functions provide the implementation for setting the width and height of a rectangle and returning the area of a rectangle, respectively.

Defining an Object

An object is an instance of a class. To define an object in C++, use the class name followed by an object name and the assignment operator =. For example, consider the following code:

1Rectangle rect1;

In this example, we define an object rect1 of type Rectangle.

Accessing Members of an Object

To access the member variables and functions of an object in C++, use the dot . operator. For example, consider the following code:

1rect1.setWidth(5); 2rect1.setHeight(3); 3cout << "Area: " << rect1.getArea() << endl;

In this example, we call the member functions setWidth and setHeight on rect1 to set the width and height of the rectangle. We then call the member function getArea to return the area of the rectangle and print it to the console.