C++ Class and Object with Example

⚡ Smart Summary

Classes and objects in C++ form the foundation of object-oriented programming, where a class defines a blueprint of data and member functions, and an object is a concrete instance created from that blueprint.

  • 🔷 Class blueprint: A C++ class bundles data members and member functions into one user-defined type.
  • 🔑 Access modifiers: The private, public, and protected keywords control where class members can be accessed.
  • 🧱 Object instantiation: An object is created from a class using the syntax class-name object-name.
  • 👉 Member access: The dot operator reaches public members, while member functions manipulate the stored data.
  • ⚙️ Constructors: Constructors initialize objects automatically, and destructors release them when they go out of scope.
  • 🤖 AI assistance: GitHub Copilot and similar AI assistants scaffold class definitions and constructors from a short comment.

C++ Class and Object

What is a Class?

A C++ class combines data and methods for manipulating the data into one. Classes also determine the forms of objects. The data and methods contained in a class are known as class members. A class is a user-defined data type. To access the class members, we use an instance of the class. You can see a class as a blueprint for an object.

A class can be a prototype for a house. It shows the location and sizes of doors, windows, floors, etc. From these descriptions, we can construct a house. The house becomes the object. It is possible to create many houses from the prototype. Also, it is possible to create many objects from a class.

C++ class as a blueprint for objects

In the above figure, we have a single house prototype. From this prototype, we have created two houses with different features.

With the idea of a class as a blueprint in mind, the next step is to see how one is declared in code.

Class Declaration

In C++, a class is defined using the class keyword. This should be followed by the class name. The class body is then added between curly braces { }.

Syntax

class class-name
   {
   // data
   // functions
   };
  • The class-name is the name to assign to the class.
  • The data is the data for the class, normally declared as variables.
  • The functions are the class functions.

Declaring the class name and body naturally raises the question of who may use each member.

Private and Public Keywords

You must have come across these two keywords. They are access modifiers.

Private:

When the private keyword is used to define a function or class, it becomes private. Such are only accessible from within the class.

Public:

The public keyword, on the other hand, makes data/functions public. These are accessible from outside the class.

After a class exists, objects can be created from it, much like variables are created from a data type.

Object Definition

Objects are created from classes. Class objects are declared in a similar way as variables are declared. The class name must come first, followed by the object name. The object is of the class type.

Syntax

class-name object-name;
  • The class-name is the name of the class from which an object is to be created.
  • The object-name is the name to be assigned to the new object.

This process of creating an object from a class is known as instantiation.

Once an object is created, its public members can be reached directly through a simple operator.

Accessing Data Members

To access public members of a class, we use the (.)dot operator. These are members marked with public access modifier.

Example 1

#include <iostream>
using namespace std;
class Phone {
public:
	double cost;   
	int slots; 
};
int main() {
	Phone Y6;        
	Phone Y7;        

	Y6.cost = 100.0;
	Y6.slots = 2;

	Y7.cost = 200.0;
	Y7.slots = 2;
	cout << "Cost of Huawei Y6 : " << Y6.cost << endl;
	cout << "Cost of Huawei Y7 : " << Y7.cost << endl;

	cout << "Number of card slots for Huawei Y6 : " << Y6.slots << endl;
	cout << "Number of card slots for Huawei Y7 : " << Y7.slots << endl;

	return 0;
}

Output:

C++ accessing public data members Example 1 output

Here is a screenshot of the code:

C++ accessing public data members Example 1 code

Code Explanation:

  1. Include the iostream header file in our code in order to use its functions.
  2. Including the std namespace in our code to use its classes without calling it.
  3. Declare a class named Phone.
  4. Using the public access modifier to mark the variables we are about to create as publicly accessible.
  5. Declare the variable cost of a double data type.
  6. Declare an integer variable named slots.
  7. End of the class body.
  8. Calling the main()function. The program logic should be added within its body.
  9. Create an object named Y6 of type Phone. This is called instantiation.
  10. Create an object named Y7 of type Phone. This is called instantiation.
  11. Access the variable/member cost of class Phone using the object Y6. The value is set to 100.0. The cost of Y6 is now set to 100.0.
  12. Access the variable/member slots of class Phone using the object Y6. The value is set to 2. The slots for Y6 is now set to 2.
  13. Access the variable/member cost of class Phone using the object Y7. The value is set to 200.0. The cost of Y7 is now set to 200.0.
  14. Access the variable/member slots of class Phone using the object Y7. The value is set to 2. The slots for Y7 is now set to 2.
  15. Print the cost of Y6 on the console alongside other text.
  16. Print the cost of Y7 on the console alongside other text.
  17. Print the number of slots for Y6 alongside other text.
  18. Print the number of slots for Y7 alongside other text.
  19. The program must return a value upon successful completion.
  20. End of the body of main() function.

Public members are open to outside code, but private members follow much stricter access rules.

What is a Private Class?

Class members marked as private can only be accessed by functions defined within the class. Any object or function defined outside the class cannot access such members directly. A private class member is only accessed by member and friend functions.

Example 2

#include <iostream>
using namespace std;
class ClassA {
public:
	void set_a(int val);
	int get_a(void);

private:
	int a;
};
int ClassA::get_a(void) {
	return a;
}
void ClassA::set_a(int val) {
	a = val;
}
int main() {
	ClassA a;
	a.set_a(20); 
	cout << "Value of a is: " << a.get_a(); 
	return 0;
}

Output:

C++ private class member Example 2 output

Here is a screenshot of the code:

C++ private class member Example 2 code

Code Explanation:

  1. Include the iostream header file in our code to use its functions.
  2. Include the std namespace in our code to use its classes without calling it.
  3. Create a class named ClassA.
  4. Use the public access modifier to mark the class member to be created as publicly accessible.
  5. Create the function named set_a() that takes one integer value val.
  6. Create a function named get_a().
  7. Use the private access modifier to mark the class member to be created as privately accessible.
  8. Declare an integer variable named a.
  9. End of the class body.
  10. Use the class name and the scope resolution operator to access the function get_a(). We want to define what the function does when invoked.
  11. The function get_a() should return the value of variable a when invoked.
  12. End of the definition of the function get_a().
  13. Use the class name and the scope resolution operator to access the function set_a(). We want to define what the function does when invoked.
  14. Assigning the value of the variable val to variable a.
  15. End of definition of the function set_a().
  16. Call the main() function. The program logic should be added within the body of this function.
  17. Create an instance of ClassA and give it the name a.
  18. Use the above class instance and the function set_a() to assign a value of 20 to the variable a.
  19. Printing some text alongside the value of variable a on the console. The value of variable a is obtained by calling the get_a() function.
  20. The program must return value upon successful completion.
  21. End of the body of function main().

Protected members sit between private and public, adding one key capability for inheritance.

What is a Protected Class?

Class members marked as protected have an advantage over those marked as private. They can be accessed by functions within the class of their definition. Additionally, they can be accessed from derived classes.

Example 3

#include <iostream>
using namespace std;
class ParentClass {
protected:
	int value;
};
class ChildClass : public ParentClass {
public:
	void setId(int x) {
		value = x;
	}
	void displayValue() {
	cout << "Value is: " << value << endl;
	}
};
int main() {
	ChildClass c;
	c.setId(21);
	c.displayValue();
	return 0;
}

Output:

C++ protected class member Example 3 output

Here is a screenshot of the code:

C++ protected class inheritance Example 3 code

Code Explanation:

  1. Include the iostream header file in our code to use its functions.
  2. Include the std namespace in our code to use its classes without calling it.
  3. Create a class named ParentClass.
  4. Use the protected access modifier to mark the class member to be created as protected.
  5. Create an integer variable named value.
  6. End of the class body.
  7. Create a new class named ChildClass that inherits the ParentClass.
  8. Use the protected access modifier to mark the class member to be created as accessible to child classes.
  9. Create the function named setId() that takes one integer value x.
  10. Assigning the value of the variable x to the variable value.
  11. End of definition of the function setId().
  12. Create a function named displayValue().
  13. Print the value of the variable named value on the console alongside other text.
  14. End of the body of the function displayValue().
  15. End of the body of the class named ChildClass.
  16. Call the main() function. The program logic should be added within the body of this function.
  17. Create an instance of ChildClass and give it the name c.
  18. Use the above class instance and the function setId() to assign a value of 21 to the variable x.
  19. Use the above class instance to call the function named displayValue().
  20. The program must return value upon successful completion.
  21. End of the body of function main().

Besides storing data, a class also groups the functions that operate on that data.

Class Member Functions

Functions help us manipulate data. Class member functions can be defined in two ways:

  • Inside the class definition
  • Outside the class definition

If a function is to be defined outside a class definition, we must use the scope resolution operator (::). This should be accompanied by the class and function names.

Example 4

#include <iostream>
#include <string>
using namespace std;
class Guru99
{
public:
	string tutorial_name;
	int id;
	void printname();
	void printid()
	{
		cout << "Tutorial id is: "<< id;
	}
};
void Guru99::printname()
{
	cout << "Tutorial name is: " << tutorial_name;
}
int main() {
	Guru99 guru99;
	guru99.tutorial_name = "C++";
	guru99.id = 1001;
	guru99.printname();
	cout << endl;
	guru99.printid();
	return 0;
}

Output:

C++ class member functions Example 4 output

Here is a screenshot of the code:

C++ class member functions Example 4 code

Code Explanation:

  1. Include the iostream header file in our program to use its functions.
  2. Include the string header file in our program to use its functions.
  3. Include the std namespace in our code to use its classes without calling it.
  4. Create a class named Guru99.
  5. Use the public access modifier to mark the class members we are about to create as publicly accessible.
  6. Create a string variable named tutorial_name.
  7. Create an integer variable named id.
  8. Create a function named printname(). This function is not defined within the class definition.
  9. Create a function named printid(). This function is defined within the class definition. Its body has been added within the class definition.
  10. Print the value of variable id alongside other text on the console. Note this has been added within the body of printid() function. It will only be executed when the printid() function is called.
  11. End of the body of function printid().
  12. End of the body of the class Guru99.
  13. The start of definition of the function printname().
  14. Print the value of variable tutorial_name on the console alongside other text. Note this has been added within the body of printname() function. It will only be executed when the printname() function is called.
  15. End of the definition of printname() function.
  16. Call the main() function. The program logic should be added within the body of this function.
  17. Create an instance of class Guru99 and giving it the name guru99.
  18. Use the above instance to assign a value of C++ to the variable tutorial_name.
  19. Use the guru99 instance to assign a value of 1001 to the variable id.
  20. Use the instance guru99 to call the function printname() .
  21. Call the end (end line) command to print a new blank line on the console.
  22. Use the instance guru99 to call the function printid().
  23. The program must return value upon successful completion.
  24. End of the body of main() function.

Two special member functions run automatically when an object is created and when it is destroyed.

Constructors and Destructors

What is a Constructor?

Constructors are special functions that initialize objects. The C++ compilers call a constructor when creating an object. The constructors help to assign values to class members. Of course, this is after they have been allocated some memory space.

What is a Destructor?

Destructors on the other hand help to destroy class objects.

The constructor name must be similar to the class name. Constructors do not have a return type.

The constructor can be defined inside or outside the class body. If defined outside the class body, it should be defined with the class name and the scope resolution operator (::).

Example 5

#include <iostream>  
using namespace std;
class ClassA {
public:
	ClassA() {
		cout << "Class constructor called"<<endl;
	}
	~ClassA() {
		cout << "Class destructor called"<<endl;
	}
};

int main() {
	ClassA a;
	int p = 1;
		if (p) {
			ClassA b; 
		}   
}

Output:

C++ constructor and destructor Example 5 output

Here is a screenshot of the code:

C++ constructor and destructor Example 5 code

Code Explanation:

  1. Include the iostream header file into the code to use its functions.
  2. Include the std namespace in our code to use its classes without calling it.
  3. Create a class named ClassA.
  4. Use the public access modifier to mark the member we are about to create as publicly accessible.
  5. Create a constructor for the class.
  6. Text to print on the console when the constructor is called. The endl is a C++ keyword, which means end line. It moves the mouse cursor to the next line.
  7. End of the body of the class constructor.
  8. Create a destructor for the class.
  9. Text to print on the console when the destructor is called. The endl is a C++ keyword, which means end line. It moves the mouse cursor to the next line.
  10. End of the body of the destructor.
  11. End of the class body.
  12. Call the main() function. The program logic should be added within the body of this function.
  13. Create a class object and give it the name a. The constructor will be called.
  14. Create an integer variable named p and assign it a value of 1.
  15. Create an if statement block using the variable p.
  16. Create a class object and give it the name b. The destructor will be called.
  17. End of the body of the if statement.
  18. End of the body of the main() function.

FAQs

A class is a user-defined blueprint that groups data members and member functions into one type. An object is a concrete instance built from that class, holding its own copy of the data described by the blueprint.

The main difference is default access: members of a class are private by default, while members of a structure are public by default. Both support inheritance, constructors, and encapsulation in C++.

C++ supports three common constructor types: a default constructor with no arguments, a parameterized constructor that accepts values to initialize members, and a copy constructor that creates a new object from an existing one of the same class.

A friend function is a non-member function granted access to the private and protected members of a class. It is declared inside the class with the friend keyword, but defined outside it like an ordinary function.

The this pointer is an implicit pointer available inside every non-static member function. It points to the object that invoked the function, letting the code refer to that object’s own members and resolve naming conflicts between parameters and data members.

Encapsulation bundles data and the functions that operate on it inside a single class, then hides internal details using private members. Public member functions expose a controlled interface, protecting the data from accidental or unauthorized access.

Yes. AI coding assistants turn a short prompt or comment into working class definitions, including data members, access specifiers, constructors, and member functions. Always review the generated access levels and initialization logic before compiling the code.

Yes. GitHub Copilot suggests class declarations, constructors, getters, and setters as you type. It handles repetitive boilerplate quickly, though you should still verify member access, constructor logic, and object usage before building.

Summarize this post with: