top of page

C++ | Classes & Objects

Updated: Jun 11, 2020

In this blog we will learn about Class and objects.


Class:

A class in C++ is that the building block, that results in Object-Oriented programming. It is a user-defined data type, which holds its own data members and member functions,which may be accessed and employed by creating an instance of that class. A C++ class is sort of a blueprint for an object.

Data members are the info variables and member functions are the functions wont to manipulate these variables and together these data members and member functions defines the properties and behavior of the objects in a Class.


Object:

An object is an instance of a Class. When a category is defined, no memory is allocated but when it's instantiated (i.e. an object is created) memory is allocated.

For example: in real world, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and brake.


Create a Class:

class MyClass
{
    public:
        int myNum;
        string myString;
};

Explanation-The class keyword is used to create a class called MyClass.

  • The public keyword is an access specifier, which specifies that members (attributes and methods) of the category are accessible from outside the category.

  • Inside the category,there's an integer variable myNum and a string variable myString. When variables are declared within a category,they're called attributes.

  • At last, end the category definition with a semicolon ; .

Create an Object:

class MyClass
{
  public:             
  int myNum;       
    string myString;
};
int main() 
{
  MyClass myObj; 
  myObj.myNum = 15; 
  myObj.myString = "Some text";
  cout << myObj.myNum << "\n";
  cout << myObj.myString;
  return 0;
}

Explanation - In C++, an object is made from a category . we've already created the category named MyClass, so now we will use this to make objects.

  • To create an object of MyClass, specify the category name, followed by the thing name.

  • To access the category attributes (myNum and myString), use the dot syntax (.) on the thing.

 

Happy Coding!

Follow us on Instagram @programmersdoor

Join us on Telegram @programmersdoor


Please write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem.

Follow Programmers Door for more.

52 views0 comments

Recent Posts

See All
bottom of page