×
>
<

Aptitude

C++ Classes And Objects | CrackEase

C++ Classes and Objects

training camping

To begin with, C++ is an object oriented programming language. The language's core features revolve around classes and objects. Classes are user-defined types that group data and behavior together.

A class can be thought of as a blueprint for objects. A class defines what data members (attributes) and member functions (methods) its objects will have. The variables and functions inside a class are called members.

An object is an instance of a class. Objects are declared similarly to variables of built-in types and each object holds its own copy of the class's data members (unless members are declared static).

What is a Class ?

When we define a class, we define a new data type. The class definition states what data each object of that type contains and what operations can be performed on it.

A class definition starts with the keyword class followed by the class name and a body enclosed in curly braces. The definition must be followed by a semicolon.

  
#include <string>

class Car
{
public:
  // to store whether a car is SUV, Sedan or hatchback
  std::string carType;	

  // to store the engine capacity
  int engineCapacity;

  // to store the model name of the Car
  std::string modelName;		
};
  

Some pointers to remember:

  • A class is a user-defined type consisting of data members and member functions.
  • Data members are variables; member functions manipulate those variables.
  • In the example above the data members are carType, engineCapacity and modelName.

Now, let us see how objects work
  
Car car1; // Declare car1 of type Car
Car car2; // Declare car2 of type Car
  
Accessing the Data Members:

The public data members of an object are accessed using the member access operator (.). Below is a complete example that demonstrates class definition, object creation and member access.

  
#include <iostream>
using namespace std;

class Car
{
public:
  double length;		// Length of a Car
  double breadth;		// Breadth of a Car
};

int main ()
{
  Car Car1;			// Declare Car1 of type Car
  Car Car2;			// Declare Car2 of type Car

  double Area = 0.0;		// Store the area of a car

  // Car 1 specs
  Car1.breadth = 3.0;
  Car1.length  = 7.0;

  // Car 2 specs
  Car2.breadth = 10.0;
  Car2.length  = 15.0;

  // Area of Car 1
  Area = Car1.length * Car1.breadth;
  cout << "Area of Car1 : " << Area << endl;

  // Area of Car 2
  Area = Car2.length * Car2.breadth;
  cout << "Area of Car2 : " << Area << endl;
  return 0;
}
  
output
  
Area of Car1 : 21
Area of Car2 : 150
  
Footer Content | CrackEase