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

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

2 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago