Unit-II
Classes and Objects
Class:
1. Class:
A class is a user-defined data type. It consists of data members and member functions, which can be accessed and used by creating an instance of that class. It represents the set of properties or methods that are common to all objects of one type. A class is like a blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with different names and brands but all of them will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage range, etc. So here, Car is the class, and wheels, speed limits, mileage are their properties
Create a Class
A class is defined in C++ using 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 at the end.
class className {
// some data
// some functions
};
When a class is defined, only the specification for the object is defined; no memory or storage is allocated.
To use the data and access functions defined in the class, we need to create objects
className objectVariableName;
We can access the data members and member functions of a class by using a . (dot) operator. For example,
room2.calculateArea();
This will call the calculateArea() function inside the Room class for object room2.
Similarly, the data members can be accessed as:
room1.length = 5.5;
In this case, it initializes the length variable of room1 to 5.5.
Defining member function :
Member functions of a class can be defined either outside the class definition or inside the class definition. In both the cases, the function body remains the same, however, the function header is different.
Outside the Class: Defining a member function outside a class requires the function declaration (function prototype) to be provided inside the class definition. The member function is declared inside the class like a normal function. This declaration informs the compiler that the function is a member of the class and that it has been defined outside the class. After a member function is declared inside the class, it must be defined (outside the class) in the program.
The definition of member function outside the class differs from normal function definition, as the function name in the function header is preceded by the class name and the scope resolution operator (: :). The scope resolution operator informs the compiler what class the member belongs to. The syntax for defining a member function outside the class is
Return_type class_name :: function_name (parameter_list) {
// body of the member function
}
To understand the concept of defining a member function outside a class, consider this example.
Example : Definition of member function outside the class
class book {
// body of the class
};
void book :: getdata(char a[],float b) {
// defining member function outside the class
strcpy(title,a):
price = b:
}
void book :: putdata () {
cout<<"\nTitle of Book: "<<title;
cout<<"\nPrice of Book: "<<price;
}
Note that the member functions of the class can access all the data members and other member functions of the same class (private, public or protected) directly by using their names. In addition, different classes can use the same function name.
Inside the Class: A member function of a class can also be defined inside the class. However, when a member function is defined inside the class, the class name and the scope resolution operator are not specified in the function header. Moreover, the member functions defined inside a class definition are by default inline functions.
To understand the concept of defining a member function inside a class, consider this example.
Example : Definition of a member function inside a class
class book {
char title[30];
float price;
public:
void getdata(char [],float); II declaration
void putdata()//definition inside the class {
cout<<"\nTitle of Book: "<<title;
cout<<"\nPrice of Book: "<<price;
} ;
The objects of a class can be passed as arguments to member functions as well as nonmember functions either by value or by reference. When an object is passed by value, a copy of the actual object is created inside the function. This copy is destroyed when the function terminates. Moreover, any changes made to the copy of the object inside the function are not reflected in the actual object. On the other hand, in pass by reference, only a reference to that object (not the entire object) is passed to the function. Thus, the changes made to the object within the function are also reflected in the actual object.
Whenever an object of a class is passed to a member function of the same class, its data members can be accessed inside the function using the object name and the dot operator. However, the data members of the calling object can be directly accessed inside the function without using the object name and the dot operator.
A Constructor in C++ is a special member function having the same name as that of its class, which is used to initialize some valid values to an object’s data members. It is executed automatically whenever an object of a class is created. The only restriction that applies to the constructor is that it must not have a return type or void. The compiler automatically calls the constructor, and it is usually used to initialize values. The compiler distinguishes the constructor from other member functions of a class by its name, which is the same as its class. ctor is an abbreviation of constructors in C++.
The constructor can be defined in the class in the same way as that of normal member functions and can access any of its data members. The syntax for defining constructors inside the class body is as follows.
class CLASSNAME {
..........
public:
CLASSNAME([parameter_list]) // constructor definition
{ ...............}
..............
};
You can also define a constructor with its declaration inside the class body and its definition outside as follows.
class CLASSNAME {
.................
public:
CLASSNAME ([parameter_list]);//Constructor Declaration
{ ...............};
CLASSNAME::CLASSNAME([parameter_list]) //Constructor Definition
{................}
The above syntax shows the declaration and definition of a constructor. It is defined outside the class in the same way as defining a member function outside the class using the scope resolution operator (::). One should note that the name of the constructor is the same as that of its class. The constructor parameter list enclosed in the square brackets is optional and may contain zero or more parameters. We should declare the constructor in the class’s public section as they are invoked automatically when the objects are created.
Note: In the constructor, the initialization includes assigning specific values to the data members and includes allocating dynamic storage and calling other member functions.
The following are the key points while defining constructors for a class:
• A constructor has the same name as that of the class to which it belongs.
• A constructor is executed automatically whenever the objects of a class are created.
• A constructor doesn’t have a return type, not even void.
• We can declare more than one constructor in a class, i.e., constructors can be overloaded. These constructors differ in their parameter lists.
• If you don’t explicitly provide a constructor of your own, then the compiler generates a default constructor for you.
• If you write any constructor explicitly with zero or more parameters, the compiler doesn’t generate the default constructor.
• A constructor can preferably be used for initialization and not for Input/Output operations.
• Like normal functions, constructors can have default arguments.
• Constructor should be declared in the public section of the class. If it is not declared in the public section (i.e., private), the whole class becomes private. The objects of the class created from outside cannot invoke the constructor, which is the first member function to be executed automatically.
• Constructors may not be static.
• Constructors are also used to allocate memory at run time using the new operator.
• You cannot call the constructor the way you call the normal function.
In addition to the above key points, the constructors also possess some additional features beyond the scope of the current topic.
• We cannot access the address of the constructors.
• An object with a constructor (or destructor) cannot be used as a member of a union.
• Constructors cannot be virtual.
• Constructors cannot be inherited, although a derived class can call the constructor of a base class.·
The various types of Constructor are as follows:
Default Constructor: Default Constructor is also called as Empty Constructor which has no arguments and It is Automatically called when we creates the object of class but Remember name of Constructor is same as name of class and Constructor never declared with the help of Return Type. Means we cant Declare a Constructor with the help of void Return Type. , if we never Pass or Declare any Arguments then this called as the Copy Constructors.
Parameterized Constructor: This is Another type Constructor which has some Arguments and same name as class name but it uses some Arguments So For this We have to create object of Class by passing some Arguments at the time of creating object with the name of class. When we pass some Arguments to the Constructor then this will automatically pass the Arguments to the Constructor and the values will retrieve by the Respective Data Members of the Class.
Copy Constructor: This is also Another type of Constructor. In this Constructor we pass the object of class into the Another Object of Same Class. As name Suggests you Copy, means Copy the values of one Object into the another Object of Class .This is used for Copying the values of class object into an another object of class So we call them as Copy Constructor and For Copying the values We have to pass the name of object whose values we wants to Copying and When we are using or passing an Object to a Constructor then we must have to use the & Ampersand or Address Operator.
#include<iostream.h>
linclude<conio.h>
class rectanqle {
private:
int length,breadth;
public:
rectangle()//constructor definition
{
length = 5; breadth = 6;
}
int area() {
return(lenqth * breadth);
}
} ;
int main() {
clrscr();
rectanqle r1;
cout<<"Area of rectangle = "<<r1.area();
qetch(); return 0;
}
Output :
Area of rectangle = 30
Explanation: In this program, whenever we create an object of the class rectangle with the statement rectangle r1, the data members length and breadth of object r1 will be initialized with the values 5 and 6, respectively, by invoking the zero parameter constructor automatically. This method of initializing data members of objects using constructors is straightforward and concise as there is no need to call the member function for each object separately explicitly.
In this program, the constructor is defined inside the class. However, we can also declare constructor rectangle() inside the class and defined outside the class as follows :
class rectangle {
.........
public:
rectangle(); //constructor declaration
};
rectangle::rectangle() // construction definition
{
length = 5;
breadth = 6;
}
A constructor to which no arguments are passed is called a default constructor. It is also called a constructor with no parameters. Using the default constructor, data members can be initialized to some reasonable value in its definition even though no arguments are specified explicitly. In the above program, the constructor rectangle::rectangle() is a default constructor.
Each time an object is created, a constructor is invoked. It can be seen in the above program. But the programs made in the previous chapters have defined objects and classes without defining any constructor for a class. So in such situations, the compiler automatically generates a constructor of its own with no parameters, i.e., default constructor. This compiler-generated default constructor is invoked automatically whenever the class’s object is created but doesn’t perform any initialization. However, if you define a default constructor explicitly, the compiler no longer generates a default constructor for you.
Every object of a class created in a program is stored somewhere in the memory. This memory is automatically deallocated when the object is destroyed. A constructor allocates resources dynamic memory) to an object during its creation in addition to its property of initialization. Similarly, we should have a member function that deallocates the resources (dynamic memory) allocated to an object. Such counterpart (complement) to the constructor is called a Destructor in C++.
A Destructor in C++ is a member function having the same name as that of the constructor (which is the same as that of class). Still, it is preceded by a tilde (~) symbol and is executed automatically when an object of a class is destroyed. Destructors are used for reinitializing the objects which are initialized by the constructors. A destructor is used to destroy the objects that the constructors already create. Like a constructor, the destructor does not have any return type, not even void, as it is invoked automatically whenever an object goes out of scope. However, unlike constructors, the destructor does not accept any parameters because there is no mechanism to pass arguments to an object destroyed. A class can have only one destructor and hence cannot be overloaded.
The syntax of the destructor is shown below.
class CLASSNAME {
........
public:
~CLASSNAME();//Destructor Declaration
..........
};
CLASSNAME:: ~CLASSNAME() //Destructor Definition
{
........... //Destructor body
}
The syntax shows that the destructor has the same name as that of the class but is “prefixed by a tilde (~) symbol from where it is distinguished from the same class’s constructor. The brackets after the destructor name show that it is a member function of a class. It must be noted that the destructor is declared in the public section of the class so that it is accessible to all its users.
If you don’t define a destructor explicitly in the class, the compiler will write one for you in the same way as the compiler generates the default constructor. The compiler-generated default destructor is primarily used for releasing the memory allocated to an object. But in certain situations, there is a need to define destructor explicitly in the class to perform some clean up of resources such as freeing memory allocated dynamically.
The following are the key points while defining a class’s destructor.
• A destructor has the same name as that of the class to which it belongs, preceded by the tilde(~) sign.
• A destructor is executed automatically whenever the object’s of a class are destroyed. It neither takes any parameters nor returns any value.
• There is only one destructor in a class and hence cannot be overloaded.
• Destructor can be used to deallocate memory for an object.
• If you don’t explicitly provide a destructor of your own, then a compiler generates a default destructor for you.
• A destructor should be declared in the public section of a class.
• It cannot be declared static or const.
• Unlike constructor, destructor can be virtual.
• Destructors cannot be inherited, though a derived class can call the base class’s destructor.
• Programmer cannot access the address of the destructor.
• An object with a destructor cannot be used as a member of a union.
class counter {
int id;
public:
counter(int i) {
id=i;
cout<<"\nconstructor of object with id" <<id<<" runs";
}
~counter() {
cout<<"\nobject with Id"<< id<< " destroyed";
}
};
int main() {
counter c1(1);
counter c2(2) ;
counter c3(3);
cout<<"\nEnd of main";
return 0;
}