CFORBEGINNERS.COM


C++ Classes, Getting Oriented

Using classes is the usually the first step to jumping into object oriented programming. Object oriented programming brings programming into the real world by dealing with objects. In our real world we deal with objects on a daily basis; cars, refrigerators, heaters, just to give some examples. Each object has components that all work together in harmony, some components the user is allowed to tweak with like a cars radio but others they are not, like the ECU which is the brains of a car and handles multiple tasks. This is much like declaring private and public variables and functions inside a class. More on that in a moment.

Sometimes getting used to using classes can prove challenging, but it's well worth the challenge. Once a programmer is comfortable with object oriented programming they gain the freedom to program in a much more realistic way. Programming with classes is the first real step in reusable code. Classes are generally used when objects share the same attributes just different values for those attributes. For example, every employee has a name, age, and salary but more than likely each employees name, age, and salary are different. Setting up these same attributes would be the class itself where setting up each individual employees name, age, and salary would be an instance of the class or object. First let us take a look at a class so we can analyze its structure. Here is the employee class.

class Employee
{
  string name;
  int age;
  double salary;
};

Class Employee is now structered the way we want it, now everytime we declare a variable of Employee type we will be adding a new individual employee or in other words object of class Employee. Each employee (object) will have a name, age, and salary thanks to our design. Also don't forget the semi-colon at the end of defining a class as this is neccesary. Declaring variables of Employee type would be juse like declaring variables of int, double, or string data type.

Employee employee1;
Employee employee2;
Employee employee3;

Notice how once a class is set up its used like any other data type. You have actually already been using classes, a string data type is just a class string thats built inside the c++ library.

string name; //string is the type and name is an object of the string class
Employee employee1; //Employee is the type and employee1 is an object of the employee class

Whenever we build a class it's known as a user defined data type, by building our own classes a programmer has the freedom to create objects that have user defined attributes and can be manipulated through functions of that same class. Just like if we wanted a variable to hold decimal values we would declare it to be a double type, and if we wanted a variable to hold a name, age, and salary of a person we would declare to be an Employee type.

Now that we have some objects declared we can access there variables through the dot operator.

employee1.name;
employee1.salary;
employee2.name;
employee3.age;

Take notice that employee1, employee2, and employee3 will not have the same values, each employees name is probably diffent as each employee (object) is an individual.

Private and Public

Declaring public and private members of a class is fundamental in programming. It just so turns out that we don't always want all of the program to be able to access and manipulate the variables inside a particular class. The method of hiding data is so fundamental in object oriented programming it even has it's own name, encapsulation. By declaring something private we restrict any function outside the class to access of that member variable or member function. Also, when something is declared public it's therefore allowed to be accessed by other functions outside the class. Both variables and functions can be declared private or public. What happens when neither private or public is declared like in the employee class above? When nothing is declared, the class members become private by default, since private or public wasn't declared inside the Employee class all three variables would become private automatically. Here is an example of the Employee class that uses both private and public.

class Employee
{
private:
  string name;
  int age;
  double salary;
  
public:
  Employee();
};

Notice that after private those are colons not semi-colons. It's also important to know that once private is declared everything will be private below the declaration until public is declared. The only member that is public in the Employee class is the constructor, which prompts another topic.

Constructor and Destructor

Constructors are neat little guys that do, well they construct. Whenever an object of a class is declared, the constructor is called, what it does when it is called is up to the programmer. You could have the constructor initialize all the variables in the class (the proper parameters must be givin to it however) or maybe only some of the variables. The constructor can simply just initialize every class member to 0 to avoid garbage, the constructor is so versatile you could even have more than one. It could even do nothing if you wanted it to. If no constructor is explicitly declared then a default constructor with no parameters is made for you. For example.

class Employee
{
private:
  string name;
  int age;
  double salary;
  
//no constructor is explicitly decalared therefore a default constructor will be created for me
//like this 'Employee ()'
};

It's important to know, that how an object of a class is declared is dependent on the constructors structure. For example, for an object that is declared with no variables a constructor with no parameters is needed and for an object that is declared with say two variables, this object would need a constructor that has two parameters. Constructors are really just special functions but they genuinely work the same way. You couldn't ever send a function more parameters than what it was originally declared to take in, a constructor is no different. Here is a more visual example of constructors.

Employee(); //constructor of employee class that takes in no parameters
Employee(string,int,double); //constructor of employee class that takes in three parameters

Now whenever an object of employee class is declared we will have the option of declaring it with no parameters or three. Be cautious however when using constructors with parameters, this is because remember how c++ automatically creates a default constructor with no parameters if no constructor is explicitly declared by you. This convenience ends when a constructor is created to hold parameters. In other words, whenver a constructor is delcared with one or more parameters c++ will no longer automatically create a no parameter constructor for you so one will have to be created manually if you wish to still declare objects with no parameters. Keep this in mind when building constructors. Alright, just like any other functions we must define what these constructors will do once they are called.

//Defining constructors

Employee()
{
 name = "";
 age = 0;
 salary = 0;
}

Employee(string n, int a, double s)
{
 name = n;
 age = a;
 salary = s;
}

The first constructor takes in no parameters but still initializes everything to 0, of course inside the curly braces could've been left empty and this would've been fine but that particular objects members would've all held garbage values. The second constructor takes in three parameters; a string, int, and double. This is ideal since an employee object holds a string, int, and double. Each member variable of the Employee class will be initialized with what was sent through the parameters. Here is an example of how an employee object would be declared.

Employee employee1; //constructor with no parameters will be called
Employee employee2("Bob",25,31.20); //constructor with three parameters will be called

Employee1 will be sent to the constructor with no parameters and thus all of its members will be initialized to 0. Employee2 will be sent to the constructor with three parameters and its members will be initialized to "Bob" (name), 25 (age), and 31.20 (salary). Sorry Bob, looks like you may need to find a second job.

The constructor has a couterpart, the destructor. The destructors job is to clean up any memory that the constructor used. Because of this, the destructor is automatically called once the particular class has gone out of scope. The syntax for the destructor is the '~' followed by the classes name.

~Employee();

Just like with the constructor, if no desturctor is declared a default constructor is created for you. So far, here is the employee class with the constructors, destructors, and main added.

Full Working Program
#include <iostream>
#include <string>
using namespace std;

class Employee
{
public:
  string name;
  int age;
  double salary;

public:
  Employee()
  {
   name = "";
   age = 0;
   salary = 0;
  }

  Employee(string n, int a, double s)
  {
   name = n;
   age = a;
   salary = s;
  }

  ~Employee()
  {
  
  }
};

int main()
{
  Employee employee1;
  Employee employee2("Steve",23,392.45);
  
  //employee1 needs to be given values
  employee1.name = "Tom";
  employee1.age = 38;
  employee1.salary = 1100.00;
  
  cout<<"Employee1:"<<endl;
  cout<<employee1.name<<endl;
  cout<<employee1.age<<endl;
  cout<<employee1.salary<<endl;
  
  cout<<"Employee2:"<<endl;
  cout<<employee2.name<<endl;
  cout<<employee2.age<<endl;
  cout<<employee2.salary<<endl;
  
return 0;
}

The constructors were defined inside the class which is perfectly legal, in the next section however I will demonstrate a more organized way to declare and define constructors, destructors, and functions. In main, two objects of the Employee class are declared, employee1 uses the default constructor and employee2 takes advantage of the three parameter constructor. Something important to take notice is how in the Employee class all the variables are public and not private. This allows main to access object members like employee1.name and so on, because main has access to these members it can intialize and print them out like normal variables. For simplicity Employees members have been made public but this isn't good practice.