type class
in C++
The concept of class inC++
A class is a new type that is defined by a keyword class
and this type can contain functions, variables, arrays, etc.
The type you define with a word class
is very similar to the type you define with the word struct
we learned in the previous lesson.
For this reason, we will start by mentioning the difference between them so that you do not get confused by the similarity that you will notice between them.
The main difference between the type defined by the word class
and the type defined by the word struct
is that the latter is directly accessible to anything in it, while in the type class
you determine whether the things you put in it are directly accessible or not.
The ability to specify the way in which the objects in the class can be accessed enables us to apply all the principles of object-oriented programming(OOP)Accepted.
That is why we will focus heavily in the upcoming lessons on dealing with the class in particular.
How to define class inC++
To define a new class, we write the word class
and give it a name, then we open parentheses specifying its beginning and ending.
The following example shows how to define an empty class namedBook
.
Class definition example in C++
class Book { // Here you can define everything that the class will contain };
Technical information
In real projects, any new class we want to define, we usually create a file of its cpp
own type and put its code inside it.
Then wherever we want to deal with it we include the file it contains.
Now, in order to make the explanation simple and easy to understand, we will write the whole code inside the same file, and at the end of the lesson we will teach you how to create the class in a special file as well.
The concept of properties inC++
Properties(Attributes)They are the objects (variables, arrays, and objects) that are defined within the class and that any object we create from it will have its own copy.
Anything you intend to define in the class does not replace you with determining how to access it, as we said earlier.
To determine how to access the things that you put in the class, you can use the words designated for that, which are said toAccess Specifiers,Which of the following words.
Word | use it |
---|---|
public |
Used to specify that objects placed in the class can be accessed from anywhere. |
private |
It is used to specify that things placed in the class cannot be accessed from outside the class. |
protected |
It is used to specify that objects placed in the class are accessible when inherited. Note: We will learn about genetics in later lessons. |
note
You will know when we should use the two words private
and protected
practically in later lessons, but now it is enough to know that it is one of the options available inC++And knowing how it can be placed inside the class.
The following example shows how to put the words public
and private
and protected
in the class.
first example
class Book { public: // public Here anything we define is considered to be private: // private here anything we define is considered to be protected: // protected Here anything we define is considered to be };
In the following example we have defined a class whose name is defined Book
and inside it we have defined 4 variables of their typepublic
.
Note: We did not put the two words private
and protected
in the class because we did not need them.
second example
class Book { public: string title; string author; double price; int numberOfPages; };
Create an object from a class and give it values inC++
Creating an object from a class is very easy, all you have to do is use the same method that you use to create a regular variable.
As for accessing the objects owned by the object, you can access anything in it as long as its type public
by typing the name of the object and then putting a dot and then putting the name of the thing you want to access.
In the following example we have defined a class whose name is defined Book
and inside it we have defined 4 variables of their typepublic
.
Then we create two objects from it and give values to the variables in them.
An example of creating an object from a class and giving it values in C++
#include <iostream> using namespace std; // Contains 4 variables. Book Here we have defined a class named class Book { public: string title; string author; double price; int numberOfPages; }; int main() { // book2 and the second one is called book1, the first one is called Book, here we have defined two objects from Book book1; Book book2; // book1 Here we have given values to the object variables book1.title = "C++ for beginners"; book1.author = "Mhamad Harmush"; book1.price = 9.99; book1.numberOfPages = 420; // book2 Here we have given values to the object variables book2.title = "Network 1"; book2.author = "Nadine Masri"; book2.price = 22.49; book2.numberOfPages = 310; // book1 Here we have shown the values of the object cout << "Book 1 ----------- \n"; cout << "Title: " << book1.title << "\n"; cout << "Author: " << book1.author << "\n"; cout << "Price: " << book1.price << "$\n"; cout << "Number of pages: " << book1.numberOfPages << "\n\n"; // book2 Here we have shown the values of the object cout << "Book 2 ----------- \n"; cout << "Title: " << book2.title << "\n"; cout << "Author: " << book2.author << "\n"; cout << "Price: " << book2.price << "$\n"; cout << "Number of pages: " << book2.numberOfPages; return 0; }
• We will get the following result when running.
Book 1 ----------- Title: C++ for beginners Author: Mahamad Harmush Price: $9.99 Number of pages: 420 Book 2 ----------- Title: Network 1 Author: Nadine Masri Price: $22.49 Number of pages: 310
Important concepts about classes inC++
first concept
Here we have given two examples of how to define a function within a class(Member Function)In addition to how to summon it from him.
It is very important to know that you can define class functions in two ways:
Define the function as it is inside the class.
Define the shape of the function(Function HeaderorPrototype)Only inside the class and define the content of the function(Function Body)outside the definition of class.
In the following example, we have defined a class whose name Book
represents the information that can be contained in any book, such as its title, author's name, price and number of pages.
We have also put a function whose name printInfo
is inside the class when called from any object we create it from, so it prints its values in an orderly manner.
Finally, we create an object from Book
and give it values, and then call the function printInfo()
from it to print its values.
first example
#include <iostream> using namespace std; // Contains 4 variables. Book Here we have defined a class named class Book { public: string title; string author; double price; int numberOfPages; // prints all the values of the variables in Book when called from any object we create from printInfo Here we have defined a function named void printInfo() { cout << "Title: " << title << "\n"; cout << "Author: " << author << "\n"; cout << "Price: " << price << "$\n"; cout << "Number of pages: " << numberOfPages << "\n"; } }; // main() Here we have defined the function int main() { // book named Book Here we have defined an object from book book; // book Here we have given values to the object variables book.title = "C++ for beginners"; book.author = "Mhamad Harmush"; book.price = 9.99; book.numberOfPages = 420; // until you print the values in book from the printInfo() object here we called the function book.printInfo(); return 0; }
• We will get the following result when running.
Title: C++ for beginners Author: Mahamad Harmush Price: $9.99 Number of pages: 420
Here we have repeated the previous example with one difference, which is that we have defined the shape of the function(Prototype) فقط بداخل الكلاس و محتواها خارجه.
المثال الثاني
#include <iostream> using namespace std; // يحتوي على 4 متغيرات Book هنا قمنا بتعريف كلاس إسمه class Book { public: string title; string author; double price; int numberOfPages; // printInfo() هنا قمنا بتعريف شكل الدالة void printInfo(); }; // و جعلناها تقوم بطباعة قيم متغيرات الكائن الذي يستدعيها Book الموجودة في الكلاس printInfo هنا قمنا بتعريف محتوى الدالة void Book::printInfo() { cout << "Title: " << title << "\n"; cout << "Author: " << author << "\n"; cout << "Price: " << price << "$\n"; cout << "Number of pages: " << numberOfPages << "\n"; } // main() هنا قمنا بتعريف الدالة int main() { // book إسمه Book هنا قمنا بتعريف كائن من Book book; // book هنا قمنا بإعطاء قيم لمتغيرات الكائن book.title = "C++ for beginners"; book.author = "Mhamad Harmush"; book.price = 9.99; book.numberOfPages = 420; // حتى تقوم بطباعة القيم الموجودة فيه book من الكائن printInfo() هنا قمنا باستدعاء الدالة book.printInfo(); return 0; }
• We will get the following result when running.
Title: C++ for beginners Author: Mahamad Harmush Price: $9.99 Number of pages: 420
second concept
Here we put an example on how to define a function that takes a parameter of an Object expression(Object Parameter)From class as well as how to summon it.
In the following example, we have defined a class whose name Book
represents the information that can be contained in any book, such as its title, author's name, price and number of pages.
Then we defined a function whose name printInfo
when called, we pass an object of its Book
type to it, and it prints its values in an orderly manner.
Finally, we create an object from Book
and give it values, and then pass it to the function printInfo()
to print its values.
Example
#include <iostream> using namespace std; // Contains 4 variables. Book Here we have defined a class named class Book { public: string title; string author; double price; int numberOfPages; }; // it prints all the values of the variables in it when called, we pass it an object from printInfo here we have defined a function named void printInfo(Book book) { cout << "Title: " << book.title << "\n"; cout << "Author: " << book.author << "\n"; cout << "Price: " << book.price << "$\n"; cout << "Number of pages: " << book.numberOfPages << "\n"; } // main() Here we have defined the function int main() { // book named Book Here we have defined an object from book book; // book Here we have given values to the object variables book.title = "C++ for beginners"; book.author = "Mhamad Harmush"; book.price = 9.99; book.numberOfPages = 420; // its until you print the values in it book and pass the printInfo() object here we called the function printInfo(book); return 0; }
• We will get the following result when running.
Title: C++ for beginners Author: Mahamad Harmush Price: $9.99 Number of pages: 420
The third concept
Here we give an example of how the operator can be used to this->
differentiate between parameters of functions and properties of the class.
This factor enables you to use the same names for parameters and properties.
The Workerthis->
is calledThis Pointer,They are used to differentiate between the parameters of functions and properties in the class, which makes you able to put the same names for the parameters and properties and avoid any logical errors due to similar names.
Now, we will give you several examples so that you can notice the logical errors that may occur due to similar names and how the operator this->
solves this problem for you.
In the following example, we have defined a class whose name Book
represents the information that can be contained in any book, such as its title, author's name, price and number of pages.
In the class, Book
by defining a function whose name setTitle()
when called, we pass a text to it and it is placed as the address of the object that called it.
first example
#include <iostream> using namespace std; // Contains 4 variables. Book Here we have defined a class named class Book { public: // Here we define the properties of the class string title; string author; double price; int numberOfPages; // Book when called from any object we create from setTitle Here we have defined a function named // owned by the title object, you set it as the value of the variable t, and we pass it the value of the parameter void setTitle(string t) { title = t; } }; // main() Here we have defined the function int main() { // book named Book Here we have defined an object from book book; // book of the title object and pass a text to it so that you store it in the book variable of the setTitle() object here we called the function book.setTitle("C++ for beginners"); // to check whether it has changed or not, the book in the title object here we print the value of the variable cout << "Title: " << book.title; return 0; }
• We will get the following result when running.
Title: C++ for beginners
If we repeat the previous example with a slight modification to it so that we make the name of the parameter in the function the setTitle()
same as the name of the variable title
in the class, we will see a logical problem when running the program, as we will see in the run result.
second example
#include <iostream> using namespace std; // Contains 4 variables. Book Here we have defined a class named class Book { public: // Here we define the properties of the class string title; string author; double price; int numberOfPages; // title We pass it a value in the place of the parameter Book when called from any object we create from setTitle Here we have defined a function named void setTitle(string title) { // the one in the title class, inside it again. That is, it will not be passed to the variable title here as we said, put back the value we pass to the parameter // because they have the same title The reason for this problem is that the compiler won't know that you mean you want to pass the value you pass to the function, to the variable title = title; } }; // main() Here we have defined the function int main() { // book named Book Here we have defined an object from book book; // book of the title object and pass a text to it so that you store it in the book variable of the setTitle() object here we called the function book.setTitle("C++ for beginners"); // to check whether it has changed or not, the book in the title object here we print the value of the variable cout << "Title: " << book.title; return 0; }
• We will get the following result when running.
• Notice that the value we passed to the function setTitle()
was not passed to the variable title
in the object book
and that's what we meant by a logical error.
Title:
To solve the problem, the region we saw in the second example, that is, to make the compiler able to differentiate between parameters and variables in the class, we will use the operator this->
whenever we want to refer to the variables in the class.
third example
#include <iostream> using namespace std; // Contains 4 variables. Book Here we have defined a class named class Book { public: // Here we define the properties of the class string title; string author; double price; int numberOfPages; // Book when called from any object we create from setTitle Here we have defined a function named // owned by the title object, you set it as the value of the variable title, and we pass it the value of the parameter void setTitle(string title) { this->title = title; } }; // main() Here we have defined the function int main() { // book named Book Here we have defined an object from book book; // book of the title object and pass a text to it so that you store it in the book variable of the setTitle() object here we called the function book.setTitle("C++ for beginners"); // to check whether it has changed or not, the book in the title object here we print the value of the variable cout << "Title: " << book.title; return 0; }
• We will get the following result when running.
Title: C++ for beginners
Fourth concept
Constructor(Builder)A distinct function that is called automatically when an object is created from a class.
This function makes it possible for you to pass the initial values of the object directly to it at the moment of its creation.
Explain the importance of the constructor inC++
One of the most important things to think about when creating a new class is to make it easier to create objects from that class later.
This is where the idea of the constructor came from(Builder)Which is a function, which is called while creating an object from a class to give initial values of its properties.
Any class that you define has a default constructor even if you define it for it yourself. The reason is that an object from a class can only be created by the constructor of that class.
That is why if you do not define a constructor for the class yourself, be sure that a language translatorC++It will create an empty default constructor for you when you try to create an object from the class.
Important points about the Constructor in C++
Each class created contains at least one constructor. Even if you don't define any constructors, the compiler will create a default one.
Every time a new object is created from a class, a constructor from the class must be called in order for that object to be created.
The basic rule when defining a constructor is that it must have the same class name and type
public
.If you define a constructor, the compiler will not create a default constructor, ie there will be no default constructor.
You can define more than one constructor. You can always create an empty constructor, so you can use it if you don't want to give specific initial values to the properties when creating an object.
In the following example, we have defined a class whose name Book
we have not defined a constructor for it.
first example
class Book { }
• The translator will automatically create a blank constructor for us as follows.
class Book { public: // This is a default constructor created by the compiler because the class does not contain any constructors Book() { } }
How to call the constructor inC++
When calling a class constructor, you must pass a value for each parameter in it by placing parentheses after the name of the object and passing the values in it.
Below we have put some examples that show how to call a constructor from a class.
If the name of the constructor is like this Book()
, then you don't need to do anything when you create an object from the class as you create it like this.
first example
book book;
If the name of the constructor is like this, Book(string title)
then you are forced to pass a value to the constructor object like this when it is created like this.
second example
Book book("C++ for beginners");
If the name of the constructor is like this, Book(string title, string author)
you are forced to pass values to the constructor object like this when it is created like this.
third example
Book book("C++ for beginners", "Mahamad Harmush");
If the class name contains an empty constructor Book()
and constructor takes two values like this Book(string title, string author)
, then you are given the option to call the constructor you want from them when creating an object from the class.
Fourth example
// You can create the object by calling the first constructor as follows Book book(); // You can create the object by calling the second constructor as follows Book book("C++ for beginners", "Mahamad Harmush");
A comprehensive example of dealing with a constructor inC++
In the following example, we have defined a class whose name Book
represents the information that can be contained in any book, such as its title, author's name, price and number of pages.
In the class Book
we have defined a constructor in which we can directly enter values for the properties of any object we create from the class.
We also defined a function whose name printInfo()
, when called, prints the property values owned by any object we create from the class.
A comprehensive example of dealing with a constructor in C++
#include <iostream> using namespace std; // Contains 4 variables. Book Here we have defined a class named class Book { public: // Here we define the properties of the class string title; string author; double price; int numberOfPages; // Here we have defined a constructor to which 4 values must be passed when it is called Book(string title, string author, double price, int numberOfPages) { // Here we have put the values we pass to the constructor in order in the object properties this->title = title; this->author = author; this->price = price; this->numberOfPages = numberOfPages; } // prints all the values of the variables in Book when called from any object we create from printInfo Here we have defined a function named void printInfo() { cout << "Title: " << title << "\n"; cout << "Author: " << author << "\n"; cout << "Price: " << price << "$\n"; cout << "Number of pages: " << numberOfPages << "\n"; } }; // main() Here we have defined the function int main() { // By passing the values we want to put in it directly through the book constructor called Book here we have defined an object from Book book("C++ for beginners", "Mahamad Harmush", 9.99, 420); // until you print the values in book from the printInfo() object here we called the function book.printInfo(); return 0; }
• We will get the following result when running.
Title: C++ for beginners Author: Mahamad Harmush Price: $9.99 Number of pages: 420
Fifth concept
Doctor(Destructor)A distinct function that is called automatically when the object is flushed from memory.
This function enables you to do any operation you want directly before the object is deleted from memory.
Explain the importance of the doctor inC++
Doctor(Destructor)A distinct function that is called automatically when the object is flushed from memory.
This function enables you to do any operation you want directly before the object is deleted from memory.
Any class you define, has a default destroyer even if you define it for it yourself and is called automatically immediately if before the object is erased from memory.
Important points about the doctor in C++
Every class that is created contains a Destructor. That is, even if you don't define a Destructor yourself, the compiler will create a default one for you.
The director is called automatically when the object is erased from memory.
The basic rule when defining a dictator is that it must bear the same name as the class and before it a symbol
~
and its typepublic
.You can define only one director in the class.
Parameters cannot be set in the dispenser.
When will the Doctor be called? C++ ?
If the object is created inside a function and all the content of the function is executed because it is normal that anything defined in it will be deleted after it is executed.
If all the program commands placed inside the function are executed
main()
because it is normal that anything defined in it will be deleted after it is executed.If the object has been deleted from memory in any other way.
Examples of the doctor inC++
In the following example, we have defined a class named after Book
it, and in it we have defined a default constructor that prints the sentence "Constructor is called"
when it is called, and a director that prints the sentence "Destructor is called"
when it is called.
Remember: the constructor will be called when an object is created from the class, and the constructor will be called automatically when the object is erased from memory.
An example of a doctor in C++
#include <iostream> using namespace std; // Contains 4 variables. Book Here we have defined a class named class Book { public: // Here we have defined the constructor that we will call when we create an object from the class Book() { cout << "Constructor is called" << endl; } // Here we have defined the Script that will be called automatically when the object is deleted from memory ~Book() { cout << "Destructor is called" << endl; } }; // main() Here we have defined the function int main() { // So the print command in the Constructor Book will be executed. Here we have defined an object from book book; // Since the program is finished here, this means that the print command in the scribe will be executed return 0; }
• We will get the following result when running.
Constructor is called Destructor is called
Sixth concept
friendly function(Friend Function)A function that can access anything an object has, even if an object in the class has its type private
or .protected
.
Explain the concept of the friendly function inC++
friendly function(Friend Function)A function that can access anything an object has, even if an object in the class has its type private
or .protected
.
What are the conditions for defining a friendly function in C++
To put the form of the function(Prototype)Only inside the class and its content(Body)outside the class.
When you put the function form inside the class, you should mention the word
friend
, but you shouldn't mention it when you write the function's content outside the class.In the class, it does not matter where you put the shape of the function(Prototype),That is, it does not matter if you make it
public
orprivate
orprotected
.Function content(Function Body)It must be defined outside the class.
For a function to have a parameter that is an object of the class in which you intend to access anything in it.
Comprehensive example of defining a friendly function inC++
In the following example, we have defined a class whose name Demo
contains 4 variables, each of them has its ownModifierDifferent.
Then we defined a friendly function whose name printValues
when called, we pass an object from the class Demo
to it, and it prints its values in an orderly manner.
Finally, we create an object from Demo
and give it values, and then call the function printValues()
from it to print its values.
Comprehensive example of defining a friendly function in C++
#include <iostream> using namespace std; // Contains 4 variables and a friendly Demo function. Here we have defined a class named class Demo { // printValues Here we have defined the form of the friendly function friend void printValues(Demo demo); int a = 1; public: int b = 2; private: int c = 3; protected: int d = 4; }; // in the first one is friend and note that we don't put the word printValues here we have defined the content of the friendly function void printValues(Demo demo) { cout << "a = " << demo.a << "\n"; cout << "b = " << demo.b << "\n"; cout << "c = " << demo.c << "\n"; cout << "d = " << demo.d << "\n"; } // main() Here we have defined the function int main() { // demo named demo here we have defined an object from demo; // its until you print the values in the demo and pass the printValues() object here we called the function printValues(demo); return 0; }
• We will get the following result when running.
a = 1 b = 2 c = 3 d = 4
Seventh concept
Here we have given an example of how to define a function that takes a parameter of its type as a pointer to a class object(Pointer to class)Plus how to summon it.
Dealing with a class pointer is exactly the same as dealing with a pointerfor struct
.
So to access things in a pointer to a class object we use the operator ->
, not the .
usual operator.
In the following example, we have defined a class whose name Book
represents the information that can be contained in any book, such as its title, author's name, price and number of pages.
Then we defined a function whose name printInfo
when called, we pass to it the address of an object that Book
is in memory, and it prints its values in an orderly manner.
Finally, we create an object from Book
and give it values, and then pass its address in memory to the function printInfo()
so that it prints its values.
Example of defining a function that takes a parameter of its type as a pointer to an object of a class ( Pointer to class ) Plus how to summon it.
#include <iostream> using namespace std; // Contains 4 variables. Book Here we have defined a class named class Book { public: string title; string author; double price; int numberOfPages; }; // it prints all the values of the variables in it when called, we pass it the address of an object from printInfo here we have defined a function named void printInfo(Book* book) { cout << "Title: " << book->title << "\n"; cout << "Author: " << book->author << "\n"; cout << "Price: " << book->price << "$\n"; cout << "Number of pages: " << book->numberOfPages << "\n"; } // main() Here we have defined the function int main() { // book named Book Here we have defined an object from book book; // book Here we have given values to the object variables book.title = "C++ for beginners"; book.author = "Mhamad Harmush"; book.price = 9.99; book.numberOfPages = 420; // its until you print the values in it book and pass the address of the printInfo() object here we called the function printInfo(&book); return 0; }
• We will get the following result when running.
Title: C++ for beginners Author: Mahamad Harmush Price: $9.99 Number of pages: 420
Eighth concept
Common things(Static Members)Anything that is defined in the class in such a way that it is uniform for all the objects from which it is created.
Explain the concept of things in common inC++
Common things(Static Members)Anything that is defined in the class in such a way that it is uniform for all the objects from which it is created.
In general, to make the thing that is defined in the class common to all the objects that we may create from it we use the word static
as we will see shortly in the examples.
What are the benefits of the things in common? C++
Common objects have many uses and benefits. For example, if you want all objects that are created from a specific class to have the same value of a variable in that class, you can set the type of the variable static
and then it will be shared among all objects.
In terms of memory, since the shared variable is the same for all objects that are created from the same class, this means that if you create 50 objects from the class, 50 copies of the variable will not be created in memory, but there will be one copy of it shared among all objects.
In this lesson, we will learn how to define common variables and functions and how to deal with them.
Explanation of covariates in C++
Defining the variable in the class as a shared variable makes you able to access the value of this variable directly from the class, that is, without the need to create an object from it.
When defining the covariate, you are not allowed to give it an initial value inside the class since you have to give it an initial value outside the class.
After assigning an initial value to the shared variable, you can change its value later through any object that has access to it.
The common variable must be defined in two stages:
It must be defined within the class without giving it an initial value, noting that its type must be specified
static
.It should be given an initial value outside of the class.
In the following example, we define a class whose name Demo
contains a regular variable named x
and a common variable namedy
.
The y
covariate is given 0
as an initial value outside the class as it is assumed.
Then we create three class objects and give a different value to each object's Demo
variable .
Finally, we change the value of the common variable once to see how it changes for all objects.x
y
Example in covariates in C++
#include <iostream> using namespace std; // Demo Here we have defined the class class Demo { // y and the common variable x here we have defined the variable public: int x; static int y; }; // the value 0 as the initial value y here we have given the common variable int Demo::y = 0; // main() Here we have defined the function int main() { // Demo Here we have defined three class objects demo demo1, demo2, demo3; // owned by each object we created x here we changed the value of the variable demo1.x = 10; demo2.x = 20; demo3.x = 30; // owned by each object we created x here we have printed the value of the variable cout << "demo1.x = " << demo1.x << endl; cout << "demo2.x = " << demo2.x << endl; cout << "demo3.x = " << demo3.x << endl; // which is the same for all objects and of course now its value is 0 because we did not change its initial value of y here we print the value of the common variable cout << "Demo.y = " << demo1.y << endl; cout << "Demo.y = " << demo2.y << endl; cout << "Demo.y = " << demo3.y << endl; // demo1 to 5 through object y here we have changed the value of // it will be considered changed for all objects because they are shared between them demo3, demo2 or demo1 Note: whether we change them through the object demo1.y = 5; //demo1 again to check if it is really set to 5 or not for all objects, not just y. Here we print the value of the common variable cout << "Demo.y = " << demo1.y << endl; cout << "Demo.y = " << demo2.y << endl; cout << "Demo.y = " << demo3.y << endl; return 0; }
• We will get the following result when running.
demo1.x = 10 demo2.x = 20 demo3.x = 30 Demo.y = 0 Demo.y = 0 Demo.y = 0 Demo.y = 5 Demo.y = 5 Demo.y = 5
Explanation of common functions in C++
The idea of shared functions is simply to define a function in Class that can be called directly from it without having to create an object from it.
A function that is defined as a common function can only handle common variables, ie those of the same type static
.
Defining a common function is the same as defining a regular function with the word added static
to it.
In the following example, we will use a common variable and function to see how many objects are created from the class.
In the beginning we defined a class whose name Demo
contains a common variable named counter
and a common function whose name getCounter
when called returns counter
only the value of the variable.
In the class, Demo
we modified the default constructor to make it add 1
to the value of the variable counter
whenever it is called.
In other words, whenever we create an object - through the virtual constructor - it will be added 1
to the value of the variable counter
, so the value coutner
will represent the number of objects created from the classDemo
.
In the end, we created three objects from the class Demo
and then called the function getCounter()
to see how many objects were created.
Example of common functions in C++
#include <iostream> using namespace std; // Demo Here we have defined the class class Demo { public: // counter Here we have defined the common variable static int counter; // Whenever counter is called here we define the constructor and set it to 1 over the value of the common variable Demo() { counter++; } // Only when counter is called and we say it returns the value of the common getCounter() here we have defined the common function static int getCounter() { return counter; } }; // the value 0 as an initial counter here we have given the common variable int Demo::counter = 0; // main() Here we have defined the function int main() { // Demo Here we have defined three class objects demo demo1, demo2, demo3; // To print the number of objects from which the Demo was created from the getCounter() class here we called the function cout << "total created object = " << Demo::getCounter(); return 0; }
• We will get the following result when running.
total created object = 3