A class is a user-defined data template consisting of a collection of related variables and functions bundled together as a single entity. The variables can be of any other type, including other classes. Within a class, variables hold the data and the code that operates on the data is contained in functions. Collectively, the functions and variables that constitute a class are called members of the class. A variable declared within a class is called a member variable, and a function declared within a class is called a member function. Grouping these is called encapsulation. Encapsulation makes it possible for other programs to use the class without knowing how it works.
Declaring a Class
A class is defined in C++ using the keyword class followed by the name of the class. The body of the class is defined inside the curly brackets and terminated by a semicolon.
Defining an Object
An object is just an individual instance of a class. When a class is defined, no memory is allocated until it is instantiated. To instantiate the class type the class name followed by the variable name or place the class name directly after the declaration after the closing bracket
Accessing Class Members
Data members and member functions of a class can be accessed using the dot(‘.’) operator with the object followed by the name of member variables or member functions.
A Simple Class
The code below creates a class box containing 3 public member variables. Since the variables have been declared public, they can be accessed outside the class definition. Two objects of class box are instantiated and each member variable is initialised with a value. The total volume of the box is calculated by multiplying the individual box variables.
#include <iostream> using namespace std; class box //class definition named box { public: int length;//declare public variable length int height;//declare public variable height int width;//declare public variable width } box1;//instantiate class after class declaration (optional) int main() { box1.height=5,box1.length=30,box1.width=20;//set values of box1 member variables cout << "Dimensions of box1 are - " << box1.height*box1.length*box1.width;//output box size box box2;// instantiate class box 2 box2.height=5,box2.length=30,box2.width=20;//set values of box2 member variables cout << "\nDimensions of box2 are - " << box2.height*box2.length*box2.width;//output box size return 0; }
Member Functions
Member functions are operators and functions declared as members of a class. Every class member function that is declared must be defined. Class functions like other normal functions can have parameters and return a value. There are 2 ways to define a member function:
Outside Class Definition-To define a member function outside the class definition we have to use the scope resolution operator :: along with class name and function name
Inside Class Definition-For those member functions inside the class definition no scope resolution operator is necessary. The function can be defined in the same way as a normal function.
Private, Protected, or Public Members
A class can contain private, protected or public members. By default, all items defined in a class are private. This means that private members can be accessed only within the functions of the class itself. Public members can be accessed outside the class and protected members are accessible in the class that defines them and in classes that inherit from that class. Keeping member data private limits access and controls how their values can be changed. Although member variables can be public, it’s considered good programming practice to keep them all private and make them accessible only via the class functions. A function used to set or get the value of a private member variable is called an accessor.
Constructors
Constructors are special class members called every time an object of that class is instantiated. This makes a constructor a perfect place to initialise class member variables. The constructor is a member function with the same name as the class but no return value. There are 3 types of constructors:
Default Constructors
The default constructor is any constructor that takes no parameters. If not defined by the programmer it is provided by default from the compiler.
Copy Constructors
A copy constructor is a member function which initialises an object using another object of the same class. This will be explained in detail later
Parameterised Constructors
Is a constructor which takes parameters. To create a parameterised constructor, add parameters to it the same way that parameters are initialised in any other function. Using a parameterised constructor enforces the program to supply a necessary variable value as a prerequisite to creating an object.
Constructor with Initialisation Lists – An initialiser list sets class data member’s values. The members to be initialised are listed after the initial parameter declaration and preceded by a colon. Each member variable to be initialised will be listed along with the parameter declaration surrounded by parentheses. This initialisation value can be a parameter or a fixed value.
In the worked example below the box class above is extended to include a constructor to initialise the member variable: length, height and width
#include <iostream> using namespace std; class box //class definition named box { public: int boxsize(); box(int,int,int); private: int length;//declare public variable length int height;//declare public variable height int width;//declare public variable width }; //constructor with optional default values box::box(int heightp=10,int lengthp=10,int widthp=10):height(heightp),length(lengthp),width(widthp) { height=heightp,length=lengthp,width=widthp; } int box::boxsize() { return height*length*width; } int main() { box box1;//create object box1 using default values cout << "Dimensions of box1 are " << box1.boxsize();//output box1 size box box2(10,20,30);//create object box2 passing user defined value cout << "\nDimensions of box2 are " << box2.boxsize();//output box2 size }
Since the assignment costs using initialiser lists are lower, there is a slight performance advantage over assigning values inside the class body.
Destructors
A Destructor is a member function called automatically when the class object goes out of scope. This happens when:
(1) the function ends or blocks ends
(2) the program ends
(3) the delete operator is called
Destructors have the same name as the class but are preceded by a tilde (~). Destructors don’t take any argument and don’t return anything. If not defined by the programmer the destructor is provided by default by the compiler.
Friend Functions
A friend function has the right to access all private and protected members of the class but is defined outside the class scope. The declaration of a friend function should be made inside the body of the class using the keyword friend.
In the code section below the friend function output is used to access the private string name.
#include <iostream> using namespace std; class UserDetails { private: string name; public: UserDetails(): name("john") { } //friend function friend string output(UserDetails); }; // friend function definition string output(UserDetails f) { //accessing private data from non-member function return f.name; } int main() { UserDetails f; cout<<"Distance: "<< output(f); return 0; }
Static Class Members
Static members are class functions not associated with the objects of that class. A static function can access other static members (functions or variables) declared in the same class. A static member can be called using the class name and the scope resolution operator instead of its objects. Since a static member is created and initialised once, there is only one copy of the static member. This single copy is available to all class objects regardless of how many class objects are created. Static members do not have access to this pointer of the class.
In the code section below a static member variable is used to keep track of the number of class user objects.
#include <iostream> using namespace std; class User { public: static int objectCount; // Constructor definition User(string n="peter", int a = 32 , string s = "m") { cout <<"Constructor called." << endl; name= n; age = a; sex = s; // Increase every time object is created objectCount++; } void userdetails() { cout << "name-" << name << " age-" << age << " sex-" << sex; } static int getCount() {//return objectCount return objectCount; } private: string name; int age; string sex; } user1; // Initialise static member of class Box int User::objectCount = 0; int main(void) { //output number of objects cout << "Object " << User::getCount()<< endl; user1.userdetails();//output object details cout << endl; User user2("mark",32,"m");//create second object cout << "Object " << User::getCount()<< endl;//output number of object //output object details user2.userdetails(); return 0; }
Const Class Objects and Member Functions
Const Classes – instantiating a const class means that once a const class object has been initialised via a constructor, any attempt to modify the object member variables is disallowed. This includes changing member variables directly or calling member functions that set the value of member variables. Any initialisation is done via class constructors:
Const Member functions – If a member function is declared as constant, it indicates that the function won’t change the value of any class members. To declare a function as constant, put the keyword const after the parentheses –
void function() const;
It is considered good programming practice to use constant functions to avoid accidental changes.
Organising Class and Function Definitions
Class definitions are often kept separate from the source code of C++ programs. Each function declared for a class must have a definition. Like normal functions, the definition of a class function has a header and a body. The definition must be in a file that the compiler can find and will usually be a file with an extension .cpp. Although you can put the declaration in the source code file, most programmers put the declaration in a header file usually ending with the file extension .hpp (or less commonly .h or .hp ).
Anonymous Classes in C++
An Anonymous class is a class declared without an identifier. It is both declared and instantiated at the same time. Since anonymous classes have no identifier there is no way to refer to them beyond the point where they are created and therefore cannot be passed as arguments to functions or be used as return values from functions. Anonymous classes also differ from regular classes in that they have no constructor. The code section below illustrates the declaration of an anonymous class –
#include <iostream> using namespace std; class //anonymous class definition { public: int length;//declare public variable length int height;//declare public variable height int width;//declare public variable width } box1;//instantiate anonymous class int main() { box1.height=5,box1.length=30,box1.width=20;//set values of box1 member variables cout << "Dimensions of box1 are " << box1.height*box1.length*box1.width;//output box size return 0; }