Classes and Objects in C++
Object-oriented programming centers on the creation of classes, which provide a general framework for organizing computations in a program, where objects are merely instances of classes.
In object-oriented programming, encapsulation may be the most useful feature of classes.
In simple terms, a class is a user-defined data type with its own data members and member functions, which are accessible and usable by creating an instance of the class. A class is often referred to as an object's blueprint.
As an example, let's take a look at the class of cars. There are many cars with different names and brands, but they all have common properties; they all have four wheels, speed limits and mileage. So, Car is the class, and wheels, speed limits and mileage are its properties.
Class definition
Defining a class is the same as defining a model for a data type, which does not define data but rather specifies what an object of the class will consist of and what operations can be performed on it.
In a class definition, the keyword class is followed by the class name, followed by a pair of curly braces enclosing the body of the class. A class definition must be terminated by a semicolon or list of declarations.
Syntax
class className{ Access_Specifier : // public, private or protected data_type Property_name; // ... other properties memeber_function(); // method to access properties };
Example
Here is how we have defined the data type Car using the class keyword:
class Car{ private: int NB_wheels; double speed; int mileage; public: int Id; void ride(){} };
The keyword "public" determines the access specifiers for the members of the class. In the next lesson, we will discuss the possibilities of specifying class members as private or protected. Public members can be accessed from outside the class object anywhere within the scope of the class object.
Define objects
The definition of a class only specifies the object specification. No memory or storage is allocated. To use the data and access functions defined in the class, objects must be created.
Syntax
className object_Name;
Example
Car c1, c2;
There will be two copies of the data members in the two objects c1 and c2.
Access members
Objects with public members can be accessed using the dot (.) access operator. To clarify, let's consider the following example.
Example
class Car{ private: int NB_wheels; double speed; int mileage; public: int Id; void ride(){ cout << "Car " << Id << " is on its way " << endl; } }; int main() { Car c1, c2; c1.Id = 1; c2.Id = 2; c1.ride(); c2.ride(); return 0; }
Output
Car 1 is on its way Car 2 is on its way
The dot (.) member access operator cannot be used directly for accessing private or protected members. We will learn how to access private and protected members in the following courses.