Writing Classes in separate files using C++ - ProgrammerTech
Language:

Search

Writing Classes in separate files using C++

  • Share this:
Writing Classes in separate files using C++

Writing Classes in separate files using

Separating the class file from the main file, we want to separate the class that we created in the previous lesson and everything related to the class in another file, and we want in the main file only the main function so that the code is more clear and more divided.

 

Steps to separate the class from the main . file

Since the beginning of the course we have worked on CodeBlocks, leaving the project we created in the previous lesson.

And we click on the word File in the far left of the program from the top bar, then we choose New, any new file because we only want to add a file to this project, and then we choose Class.

Create a new class in C++

 

Then we write the name of the class as it is in the Main file, we have the class named Student, we write its name as shown in the figure.

إنشاء كلاس جديد مفصول عن الملف main

 

After that, we click on Create, and two new files will be created for us, which are Student.h and Student.cpp, as shown in the figure.

فصل ملف الكلاس عن الملف الرئيسي

 

And inside the two files that we created, their default codes will be

Student.h . file

The class file is separated from the main file in c++

 

Student.cpp . file

How to separate the class from the main file

 

In the previous lesson, we said that the first part of the program is called the class header, which will be placed in the Student.h file.

We will cut it from the previous lesson code and paste it in Student.h as follows.

#include <iostream>
using namespace std;
#ifndef STUDENT_H
#define STUDENT_H
class Student{
private:
    string name;
    double grade;
public:
    Student(string n, double g);
    void setName(string n);
    void setGrade(int g);
    string pass();
    void printStatus();
};
#endif // STUDENT_H

And in Student.cpp which is called working file we delete all existing default codes.

We notice at the beginning that the word Student is written between double quotes “” and not signs greater than and less than <>.

The difference between them is that the double quotes means that this file is in the project.

Include iomanip is for libraries that should be fetched from outside and not files written in this file.

And in the file Student.cpp we cut what was under the main in the example of the previous lesson and paste it there as follows.

#include "Student.h"
    Student::Student(string n, double g)
    {
        setName(n);
        setGrade(g);
    }
    void Student::setName(string n)
    {
        name = n;
    }
    void Student::setGrade(int g)
    {
        grade = g;
    }
    string Student::pass()
    {
        return (grade > 60 ? "yes" : "no");
    }
    void Student::printStatus()
    {
        cout << "Name : " << name << endl;
        cout << "Degree : " << grade << endl;
        cout << "Success : " << pass() << endl;
        cout << endl;
    }

And the main file will only write the values, i.e. student tags.

And in order to define the class, we write include "Student.h" at its beginning, as in the following code..

#include <iostream>
#include "Student.h"
using namespace std;
int main()
{
    Student saja("Saja", 100);
    saja.printStatus();
    Student data("Mohammad", 30);
    data.printStatus();
    return 0;
}

When we run the previous program, we will get the following result

Name: Saja
Degree: 100
Success: yes
Name: Mohammad
Degree: 30
Success: no

Practical 1

Create a class for a rectangle and the properties of the rectangle are length and width of type float.

The first two functions must be created that returns the area of ​​a rectangle and the area of ​​the rectangle is the length times the width.

The second function returns the perimeter of the rectangle and the perimeter of the rectangle is equal to two times the length + width.

And we must create functions set and get and all variables are of type private.

The set function checks whether the entered value is less than or equal to 20 and greater than 0 for both functions.

Our class will be called Rectangle.

  • main . file
#include <iostream>
#include "Rectangle.h"
using namespace std;
int main()
{
    Rectangle rect = Rectangle(3, 2);
    cout << "The length of the rectangle is" << rect.getHeight() << endl;
    cout << "susceptible" << rect.getWidth() << endl;
    cout << "its area" << rect.area() << endl;
    cout << "surroundings" << rect.perimeter() << endl;
    return 0;
}

In this file we just created a rect object derived from the class Rectangle and set it to length 3 and width 2.

Then we put the print commands at the beginning that prints the length of the rectangle by calling the getHeight function via the rect object.

This is followed by printing the width of the rectangle by calling getWidth.

And then we asked him to print the area of ​​this rectangle via area and as we know that the area of ​​the rectangle is the length times the width.

Then we asked to print the perimeter of this rectangle and its perimeter is the sum of the length and width multiplied by two 2.

  • Rectangle.h . file
#ifndef RECTANGLE_H
#define RECTANGLE_H
class Rectangle{
private:
    int height, width;
public:
    Rectangle(int, int);
    /Function
    int area();
    int perimeter();
    /Setters
    void setHeight(int);
    void setWidth(int);
    /Getters
    int getHeight();
    int getWidth();
};
#endif

We have created a class called Rectangle with two int variables of height and width.

Then we created a public constructor and in it we put the variables of the functions which are area for area and perimeter for perimeter.

The functions of the Setters are setHeight and setWidth, and their type is int.

And the Getters functions are for getHeight and setWidth, then we close the class.

  • Rectangle.cpp . file
#include "Rectangle.h"
    /Function
Rectangle::Rectangle(int h, int w)
{
    setHeight(h);
    setWidth(w);
}
int Rectangle::area()
{
    return height * width;
}
int Rectangle::perimeter()
{
    return 2*(height + width);
}
    /Setters
    void Rectangle::setHeight(int h)
    {
        height = h;
    }
    void Rectangle::setWidth(int w)
    {
        width = w;
    }
    /Getters
    int Rectangle::getHeight()
    {
        return height;
    }
    int Rectangle::getWidth()
    {
        return width;
    }

Here we put the constructor at the beginning and we put the functions that belong to the class and we accessed them by adding the name of the class and after it two points::.

We pass setHeight through the letter h and setWidth through the letter w.

And we came up with the area variable and we set it to give us the length times the width.

And then we came to the perimeter variable and asked him to return to us the product of adding the length and width multiplied by the number two.

Then we defined the Setters and Getters functions with setHeight to return h and setWidth to return w.

and that getHeight returns height and getWidth returns width.

And when we run the code, we will get the following result.

The rectangle is its length: 3
susceptible: 2
area: 6
surroundings: 10

We notice from the previous result that he gave us the rectangle with length 3, width 2 and area 6, which means length multiplied by width and perimeter 10, which is width plus length multiplied by 2.

Practical 2

Create a User class so that the user is allowed to create a new user by entering the username and password and record this data in an array.

#include <iostream>
using namespace std;
class User
{
private:
    string username, password;
public:
    void setUsername(string u)
    {
        username = u;
    }
    void setPassword(string p)
    {
        password = p;
    }
    string getUsername()
    {
        return username;
    }
    string getPassword()
    {
        return password;
    }
};
int size = 0; /users number
User users[100];    /an array with 100 elements

int main()
{
    string username, password;
    while(true)
    {
        cout << "username" << " ";
        cin >> username;
        cout << "password" << " ";
        cin >> password;
        User newUser;
        newUser.setUsername(username);
        newUser.setPassword(password);
        users[size++] = newUser;
        for(int i=0; i<size; i++)
        {
            cout << i << ". " << users[i].getUsername() << endl;
        }
    }
    return 0;
}

We created a class named User and it has two variables of text type, username and password.

Then we created some global functions with Setters which are setUsername to pass the text variable u and setPassword to pass the text variable p.

And the Getters functions that getUsername returns the username and setPassword returns the password.

Then we wrote a variable called size, which means the number of users, and the count starts from 0.

And we set that the size of this array can accommodate 100 users.

Then we entered the main function and created a for loop inside a while loop in order to ask the user every time to add new data and be recorded in the array.

And when you run this program and fill it with some data, it will be as follows.

Result of the example of separating the class file from the main file

Muhammad Alush

Muhammad Alush

إسمي محمد تركي العلوش من سورية من ريف حلب الشرقي 1994, محب للتقنية و التعلم الذاتي, و جميع خبراتي تعلمتها ذاتياً, و اللغات البرمجية التي أتقنها هي html, css, javascript, php, c, python بالإضافة إلى حبي الكبير لمجال الشبكات.

موقعي programmer-tech.com