A class is a user-defined type consisting of related data and functions bundled together as a single entity. The variables and other data stored by a class represent the state of an object, while its member functions provide operations that can work on that data. The variables and functions that make up a class are called its members. A variable declared within a class is called a data member or member variable, and a function declared within a class is called a member function.
Grouping data and the functions that operate on that data within a class is an important part of encapsulation. Encapsulation allows the internal details of a class to be hidden while providing a controlled interface through which the class can be used.
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 enclosed in braces ({ }) and the class definition is terminated by a semicolon.
Defining an Object
An object is an individual instance of a class. Defining a class creates a new type, but does not by itself create an object of that type.
An object can be created by using the class name followed by the name of the object:
box box1;
Here, box is the class type and box1 is an object of that type.
Accessing Class Members
Data members and member functions of an object can be accessed using the dot () operator, followed by the name of the member..
For example:
box1.height = 5;
box1.boxsize();
Here, height is a data member and boxsize() is a member function of the box1 object.
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
Member Functions
A member function is a function that is declared as a member of a class. Like other functions, member functions can have parameters and can return a value.
A member function can be defined either inside the class definition or outside the class definition.
Outside Class Definition – To define a member function outside the class definition, the scope resolution operator (::) is used with the class name and function name:
int box::boxsize()
{
return height * length * width;
}
Inside Class Definition – A member function defined inside the class definition does not require the scope resolution operator:
int boxsize()
{
return height * length * width;
}
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 retrieve the value of a private member variable is commonly called an accessor or getter, while a function used to change its value is commonly called a mutator or setter.
Constructors
A constructor is a special member of a class that is automatically invoked when an object is created. Constructors are commonly used to initialise the object’s data members.
A constructor has the same name as the class and does not have a return type.
There are several forms of constructor, including default constructors, copy constructors and constructors that take parameters.
Default Constructors
A default constructor is a constructor that can be called without arguments. If the programmer does not declare any constructors and the conditions for an implicitly declared default constructor are met, the compiler can provide one automatically.
Copy Constructors
A copy constructor is a constructor that initialises an object using another object of the same class.
Parameterised Constructors
A parameterized constructor is a constructor that takes one or more parameters. These parameters can be used to initialise the data members of the new object. Using a parameterized constructor allows the programmer to require values when an object is created, although default arguments can also be provided.
Constructor with Initialisation Lists – A constructor can use a member-initializer list to initialise class data members. The member-initializer list appears after the constructor’s parameter list and begins with a colon (:). Each member to be initialised is followed by its initial value in parentheses or braces.
The initial value can be supplied by a constructor parameter or can be a fixed value.
box::box(int heightp = 10, int lengthp = 10, int widthp = 10)
: height(heightp), length(lengthp), width(widthp)
{
}
Here, height, length and width are initialised directly using the values supplied to the constructor.
In the example below, the box class is extended to include a constructor that initialises the length, height and width members.
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
}
Member-initializer lists are also important because class members are initialised directly rather than being default-initialised and then assigned a value. Some types of members, such as references and const data members, must be initialised using a member-initializer list.
Destructors
A destructor is a special member of a class that is automatically invoked when an object is destroyed. This normally occurs when an object reaches the end of its lifetime, such as when a local object goes out of scope, when an object created with new is destroyed using delete, or when the program terminates and objects with static storage duration are destroyed.
A destructor has the same name as the class but is preceded by a tilde (). A destructor does not take parameters and does not have a return type.~
If the programmer does not declare a destructor, the compiler can provide one automatically.
Destructors are commonly used to release resources owned by an object, although modern C++ often uses classes such as smart pointers and standard library containers to manage resources automatically.
Friend Functions
A friend functionis allowed 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
A static member belongs to the class rather than to individual objects of that class. A class can have static data members and static member functions.
A static data member has a single shared value for the class, rather than a separate copy for each object. This single value is shared by all objects of the class.
A static member function can be called using the class name and the scope resolution operator () instead of an object. Because a static member function is not associated with a particular object, it does not have access to the :: pointer and cannot directly access non-static members.this
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 Class Objects and Member Functions
Const Objects – A class object can be declared as const. Once a const object has been initialised, its state cannot be modified. A const object can only call member functions that are declared as const.
For example:
const box box1;
The object’s data cannot subsequently be changed.
Const Member Functions – A member function can be declared as const to indicate that it does not modify the object’s observable state. To declare a member function as const, place the keyword const after the function’s parameter list:
void function() const;
Const member functions can be called on both const and non-const objects. Declaring member functions as const where appropriate helps prevent accidental modification of an object.
Organising Class and Function Definitions
Class definitions are often kept separate from the implementation of a C++ program. A class declaration and its member function declarations are commonly placed in a header file, usually with an .hpp or .h extension.
Member function definitions are commonly placed in a source file with a .cpp extension. A member function defined outside the class uses the class name and scope resolution operator (::) to identify the class to which it belongs.
For example:
int box::boxsize()
{
return height * length * width;
}
Keeping declarations and definitions in separate files can make larger programs easier to organise and maintain.
Anonymous Classes in C++
An anonymous class is a class that is declared without a class name. An object of the class can be created at the same time as the class is defined.
For example:
int box::boxsize()
{
return height * length * width;
}
Here, an unnamed class is defined and an object called box1 is created at the same time.
Because the class has no name, there is no convenient way to declare additional objects of the same class or to refer to the class type elsewhere in the program. For this reason, named classes are normally used when a class needs to be used more than once.
#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;
}