Categories: C++

Classes and Objects in C++

The fundamental idea that the object-oriented approach revolves around in C++ is the concept of classes and objects. It increases the efficiency of the program by reducing code redundancy and debugging time.

Classes:

A class is the building block in C++ that leads to Object-Oriented programming. It is a user-defined data type with its own data members and member functions that can be accessed and used by instantiating the class. A C++ class is similar to an object’s blueprint.

For Instance: Consider the Automobile Classification. There may be many cars with different names and brands, but they will all have some common characteristics, such as four wheels, a speed limit, a mileage range, and so on. Car is the class, and the properties are wheels, speed limits, and mileage.

  • A Class is a custom data type with data members and member functions.
  • Data members are data variables, and member functions are functions used to manipulate these variables.
  • These data members and member functions define the properties and behavior of objects in a Class.
  • In the preceding example of class Car, the data members will be speed limit, mileage, and so on, and the member functions will be apply brakes, increase speed, and so on.
Object:

An Object is an instance of a Class. When a class is defined, no memory is allocated; however, memory is allocated when the class is instantiated (i.e. an object is created).

Syntax:

ClassName ObjectName;
Example:

#include <iostream>
using namespace std;
class Coderz
{
 // Access specifier
 public:

 // Data Members
 string name;

 // Member Functions()
 void printname()
 {
 cout << "name is: " << name;
 }
};

int main() {

 // Declare an object of class geeks
 Coderz obj1;

 // accessing data member
 obj1.name = "Rabecca";

 // accessing member function
 obj1.printname();
 return 0;
}
Output:
name is: Rabecca

Note: also read about Functions in C++

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

1 day ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

3 weeks ago

Longest Substring with K Distinct Characters

Given an integer k and a string s, write a function to determine the length…

3 weeks ago

Staircase Climbing Ways

There is a staircase with N steps, and you can ascend either 1 step or…

4 weeks ago

Autocomplete System Implementation

Build an autocomplete system that, given a query string s and a set of possible…

4 weeks ago

Job Scheduler Implementation

Design a job scheduler that accepts a function f and an integer n. The scheduler…

4 weeks ago