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 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's possible to create many houses from the prototype. Also, it's possible to create many objects from a class.

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

In this tutorial, you will learn:

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.

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.

Object Definition

Objects are created from classes. Class objects are declared in a similar way as variables are declared. The class name must start, followed by the object name. The object 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.

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:

Here is a screenshot of the 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.

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.

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 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:

Here is a screenshot of the 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().

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:

Here is a screenshot of the 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().

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 2:

#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:

Here is a screenshot of the 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 printed(). 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.

Constructors and Destructors

What is Constructors?

Constructs are special functions that initialize objects. The C++ compilers calls 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 Destructors?

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 3:

#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:

Here is a screenshot of the 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.

Summary:

  • C++ is object-oriented.
  • Classes form the main features of C++ that make it object-oriented.
  • A C++ class combines data and methods for manipulating the data into one.
  • A class is a blueprint for an object.
  • Classes determine the form of an object.
  • The data and methods contained in a class are known as class members.
  • To access class members, you should use an instance of the class.
  • To create a class, we use the class keyword.
  • The class member functions can be defined inside or outside a class.

 

YOU MIGHT LIKE: