Theory
- Classes are an expanded concept of data structures: like data structures, they can contain data members, but they can also contain functions as members.
- An object is an instantiation of a class. In terms of variables, a class would be the type, and an object would be the variable.
- Classes are defined using either keyword
class
or keyword struct, with the following syntax:
class class_name { access_specifier_1: member1; access_specifier_2: member2; ... } object_names;
Where class_name
is a valid identifier for the class, object_names
is an optional list of names for objects of this class. The body of the declaration can contain members, which can either be data or function declarations, and optionally access specifiers
.
// C++ class: class Cube { public: double getVolume(); // ... private: double length_; }; |
structures
, except that they can also include functions and have these new things called access specifiers. An access specifier is one of the following three keywords: private, public or protected. These specifiers modify the access rights for the members that follow them.The protection level determines the access that «client code» has to the member data or functionality:
Example of header-file code (Cube.h
):
#pragma once class Cube { public: double getVolume(); double getSurfaceArea(); void setLength(double length); private: double length_; }; |
Example of implementation-file code (Cube.cpp
):
#include "Cube.h" double Cube::getVolume() { return length_ * length_ * length_; } double Cube::getSurfaceArea() { return 6 * length_ * length_; } void Cube::setLength (double length) { length_ = length; } |
Example of main-file code (main.cpp
):
#include "Cube.h" int main() { Cube c; c.setLength(3.48); double volume = c.getVolume(); std::cout << "Volume: " << volume << std::endl; return 0; } |
Arguments passed by …
-
Identical to storage, arguments can be passed to functions in three different ways:
- Pass by value (default)
- Pass by pointer (modified with
*
) - Pass by reference (modified with
&
, acts as an alias)
Values returned by …
Similarly, values can be returned all three ways as well:
*
)&
, acts as an alias)Class destructor
- When an instance of a class is cleaned up, the class destructor is the last call in a class’s lifecycle.
- An automatic default destructor is added to your class if no other destructor is defined.
- The only action of the automatic default destructor is to call the default destructor of all member objects.
- An destructor should never be called directly. Instead, it is automatically called when the object’s memory is being reclaimed by the system:
- If the object is on the stack, when the function returns
- If the object is on the heap, when
delete
is used - To add custom behavior to the end-of-life of the function, a custom destructor can be defined as:
- A custom destructor is a member function.
- The function’s destructor is the name of the class, preceded by a tilde
~
. - All destructors have zero arguments and no return type.
Cube::~Cube(); // Custom destructor |
Labs and tasks
To do: Create a
Rectangle
class and an object (i.e., a variable) of this class, called rect
.1) The class should contain four members:
— two data members of type int (member
width
and member height
) with private access,— and two member functions with public access: the functions
set_values
and area
.
2) Define two member functions: set_values
function should set the variables width
and height
to the values; are function should return width*height
.
3) Create a Custom default constructor to have the initial values for width
and height
(set them to 5
).
4) Set the width
and height
values for the rect
object and print out the information about this object.
Expected output:
Lab 1: please, enter width: >> 20 please, enter height: >> 2 rect area: 40
✍ Algorithm:
- To do the lab create empty console application with a name
Lesson9
. Add files:mainLab1.cpp
,ImpLab1.cpp
,HeaderLab1.h
. - Include all the needed libraries and files.
- The class must be defined inside a header file. So, open the header file and add the code to define the class with two private data members, they are
width
andheight
; and two member functions with public access, they areset_values
andarea
. - Here
Rectangle
is the class name (i.e., the type). - The functions
set_values
andarea
have a public access, it means that they can be accessed from inside the main function by simply inserting a dot (.
) between object name and member name (e.g.rect.set_values
…). width
andheight
members cannot be accessed from outside the class, since they have private access and they can only be referred to from within other members of that same class.- Since members
width
andheight
have private access, access to them from outside the class is not allowed. So, we should define a member function to set values for those members within the object: the member functionset_values
. - Let’s create the definition of
set_values
member function. We’re going to have a member of a class outside the class itself, so, we have to use scope operator (::
, two colons). You should create the definition of the function inside the implementation file: - The second member function, that is
area
function, we’re going to have inside the class itself, just to try different ways of definition. So, return to the header file and add the definition inside the class next toint area(void)
statement: - Add the declaration of a Custom default constructor inside the public access of the class (header file):
- Open your implementation file to add the definition of that constructor:
- Open a main file in the editor window. You should create an object (i.e., a variable) of the
Rectangle
class, calledrect
. And after this, ask user to input thewidth
andheight
values. Call theset_values
function and output the result: - Run the program and check the output.
1.Create a Rectangle
class:
class Rectangle { private: int width, height; public: void set_values(int, int); int area(void); } ; |
2. Define two member functions:
void Rectangle::set_values(int x, int y) { width = x; height = y; } |
::
) specifies the class to which the member being defined belongs, granting exactly the same scope properties as if this function definition was directly included within the class definition. For example, the function set_values
has access to the variables width
and height
, which are private members of class Rectangle
, and thus only accessible from other members of the class, such as this.int area() {return width*height;} |
3) Create a Custom default constructor to have the initial values for width
and height
(set them to 5
).
public: // you had this code Rectangle(); void set_values(int, int); // you had this code //... |
Rectangle::Rectangle() { width = 5; height = 5; } |
4) Set the width
and height
values for the rect
object and print out the information about this object:
int main() { Rectangle rect; int w, h; cout << "please, enter width:\n"; cin >> w; cout << "please, enter height:\n"; cin >> h; rect.set_values(w, h); cout << "rect area: " << rect.area() << endl; system("pause"); return 0; } |
To do: Create a LessonDate
class to output the date of a lesson.
1) The class should contain the following members:
— three data members of type int with private access, they are day
, month
and year
;
— and two member functions with public access:
void setDate(int, int, int);
to set the date for the next lesson and
void getDate();
to print out the date of the lesson.
2) Create a three argument constructor to have the initial values for date; in the constructor body call the setDate
function to set the date.
3) Inside the main function create an object (i.e., a variable) of this class, called objLesson
. Set the values of three parameters — day, month and year. Print out the information about this object.
Expected output:
Task 1: Lesson date: 11.11.2021 Please, enter day, then month and year of the next lesson 28 12 2020 Lesson date: 28.12.2020
[Solution and Project name: Lesson_9task1
, file name L9Task1main.cpp
, L9Task1imp.cpp
, L9Task1.h
]
To do: Create a
Cube
class.1) The class should contain four members:
—
length_
data member of type double with private access,— three member functions with public access: the functions
double getVolume();
, double getSurfaceArea();
and void setLength(double length);
.
2) Give the definitions (implementations) of those functions:
getVolume()
function have to calculate a volume of the cube: length_ * length_ * length_;
getSurfaceArea() function have to calculate a Surface Area of the cube: 6 * length_ * length_;;
setLength(double length)
function have to set the value for the cube length.
3) Create a Custom default constructor to have the initial values for length_
(set it to 1
).
4) Inside the main cpp file create double cube_on_stack()
function to create an object (i.e., a variable) of this class and get volume of it. This object will be in a stack memory. Also, inside the main function create a new cube of length 10 which is going to be in heap memory. Set the values. Print out the information about those objects.
5) Create a custom destructor to delete an information about the cube.
Expected output:
Lab 2: Volume of c cube: Destructor called for cube with length 2 Volume of c cube in the heap memory: 27 Destructor called for cube with length 3
✍ Algorithm:
- To do the lab create an empty console application with a name
Lesson9Lab2
. Create new files:mainLab2.cpp
,ImpLab2.cpp
,HeaderLab2.h
. - Include all the needed libraries and files.
- The interface of the class must be inside a header file. So, open the header file and add the code to define the class with one private data member, it is
length_
of a cube; and three member functions with public access, they aregetVolume()
,getSurfaceArea()
andsetLength(double length)
. - Here
Cube
is the class name (i.e., the type. - The functions
getVolume()
,getSurfaceArea()
andsetLength(double length)
have a public access, it means that they can be accessed from anywhere where the object is visible. length_
member cannot be accessed from outside the class, since it has a private access and it can only be accesses from within the class itself.- Let’s create the definition of
setLength
member function. We’re going to have a member of a class outside the class itself, so, we have to use scope operator (::
, two colons). You should create the definition of the function inside the implementation cpp file: - The second and th third member functions are
getVolume
andgetSurfaceArea
function, we’re going to have them inside the implementation file too: - Add the declaration of a custom default constructor inside the public access of the class (header file):
- Open your implementation file to add the definition of that constructor:
- Open a main file in the editor window. Before the main function add the code to create cube_on_stack() which will create the object of Cube class and return the volume of this object:
- Inside the main function ptint out the message and call that function:
- Then, inside the main function you should create a new cube of length 10 which is going to be in heap memory:
- Open header file to declare a class destructor, which will be called to clean up the instance of the class. Add it right after the class constructor to the public protection level:
- Add the implementation for that destructor inside implementation file:
- Return to the main file and add the
delete
keyword to clean up the memory of thepcube
object: - Run the program and check the output.
1.The class should contain four members:
class Cube { public: double getVolume(); double getSurfaceArea(); void setLength(double length); private: double length_; }; |
2. Give the definitions (implementations) of the functions:
void Cube::setLength(double length) { length_ = length; } |
::
) specifies the class to which the member being defined belongs, granting exactly the same scope properties as if this function definition was directly included within the class definition. For example, the function setLength
has access to the variable length_
, which is a private member of the class Cube
, and thus only accessible from other members of the class, such as this.double Cube::getVolume() { return length_ * length_ * length_; } double Cube::getSurfaceArea() { return 6 * length_ * length_; } |
getVolume
function will return the volume of that cube, for which this function will be called.The
getSurfaceArea
function will return the surface area of that cube, for which this function will be called.
3) Create a custom default constructor to have the initial values for length_
(set it to 1).
public: // you had this code Cube(); //... |
Cube::Cube() { length_ = 1; } |
4) Inside the main cpp file create double cube_on_stack()
function to create an object (i.e., a variable) of this class and get volume of it:
double cube_on_stack() { Cube c; c.setLength(2); return c.getVolume(); } int main() { // ... } |
int main() { cout << "Volume of first cube: " << endl; cube_on_stack(); } |
Also, inside the main function create a new cube of length 10 which is going to be in heap memory. Set the values. Print out the information about those objects.
Cube * pcube = new Cube; pcube->setLength(3); cout << "Volume of c cube in the heap memory: " << pcube->getVolume() << endl; |
*
) sign. Such objects or instances to the objects can be used together with arrow operator to access their members.5) Create a custom destructor to delete an information about the cube.
~Cube(); |
Cube::~Cube(){ cout << "Destroyed cube with length " << length_; } |
// ... delete pcube; |
delete
keyword is used, to reclaim that memory that the object was using. To do: Create a Student
class to output information about the students.
1) The class should contain the following members:
— two data members of type string with private access, they are name
and surname
, and one data member of type int — age
;
— and two member functions with public access:
void set_info(string, string, int);
to set the information about the student
and void get_info(void);
to print out the information.
2) Create a three argument constructor to have the initial values for student.
3) Inside the main cpp file create void student_on_stack()
function to create an object (i.e., a variable) of this class and get volume of it. This object will be in a stack memory. Also, inside the main function create a new student with some info about, which is going to be in a heap memory. Print out the information about those objects.
4) create a custom destructor to delete an information about student.
Expected output:
Task 2: info about student1: name: Johnsurname: Ivanovage: 20 Destructor called for Student Ivanov info about student2: name: Petersurname: Panage: 17 Destructor called for Student Pan
[Solution and Project name: Lesson_9task2
, file name L9Task2main.cpp
, L9Task2imp.cpp
, L9Task2.h
]
To do: Create a BookShop
class to store and output an information about the selling books.
1) The class should contain the following members:
data members with private access:
— title_
(a title of a book) of type string;
— author_
(an author of a book) of type string;
— _price
(a price of a book) of type double;
— _discount
(a discount for a price of a book) of type int.
data members with public access:
— void getInfo()
function to print out the information about the book;
— void set_info(string title, string author, double price, int discount)
function to set the information about the book;
— double getTotalPrice()
function calculate the price of a book considering the discount (price — (price * discount)).
2) Create a four argument constructor to have the initial values for books.
3) Create two objects and print out the information about those objects. Print out the info about the price considering the discount.
Expected output:
Task 3: // book 1 info: Dostoevsky Demons 205 roubles, discount 0.05, total price 194,75 roubles // book 2 info: Kuprin Duel 125 roubles, discount 0.1, total price 112,5 roubles
[Solution and Project name: Lesson_9task3
, file name L9Task3main.cpp
, L9Task3imp.cpp
, L9Task3.h
]