coderz.py

Keep Coding Keep Cheering!

Classes and Objects in C++

Accessing Elements

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

Leave a Comment

Your email address will not be published. Required fields are marked *

Advertisement