Classes and Object

Introduction to Class and Object

  • Class Class is a user defined data type. A class is a logical abstraction. It is a template that defines the form of an object. A class specifies both code and data. When defined class, you declare data that it contains, and the code that operates on the data. Data is contained in instance variable defined by the class known as data members and code is contained in functions known as member functions. The code and the data that constitute a class are called members of the class.
  • Object : Object is a variable of a class. It is an identifiable entity with specific characteristics (data members) and behaviour (member functions). Defining an object is similar to defining a variable of any data type.
Example -

In the above example, as we can see, test is a class. This class has integer data member- num, and two member functions- void getdata() and void showdata().
Also, in the same program, we have t1 as a variable of class test. Hence t1 is nothing but an object of class test.

NOTE : An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory is allocated.

Defining class (class specifications)

A class is defined in C++ using keyword class followed by the name of class. The body of class is defined inside the curly brackets and terminated by a semicolon at the end.
Syntax - 

Creating Object

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, you need to create objects.
Syntax -   class_name object_name;

Access Specifier (Visibility Modes)

Access specifiers/modifiers are used to implement an important feature of Object Oriented Programming known as Data Hiding. Consider a real-life example: Consider Indian secret informatic system having 10 senior members, have some top secret regarding national security. So we can think that 10 people as class data members or member functions who can directly access secret information from each other but anyone can’t access this information other than these 10 members i.e. outside people can’t access information directly without having any privileges. This is what data hiding is.

Access modifiers or Access Specifiers in a class are used to set the accessibility of the class members. That is, it sets some restrictions on the class members not to get directly accessed by the outside functions.
There are three visibility modes for a class in C++.
  • Public: All the class members declared under the public will be available to everyone. The data members and member functions declared public can be accessed by other classes too. The public members of a class can be accessed from anywhere in the program using the direct member access operator (.) with the object of that class.
    Example
     Output -
In the above program, the data member num is public. So we are allowed to access it outside the class.
  • Private: The class members declared as private can be accessed only by the functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of a class.

The output of the above program will be a compile time error because we are not allowed to access the private data members of a class directly outside the class.

However, we can access the private data members of a class indirectly using the public member functions of the class. Below program explains how to do this:

Output -
  • Protected: Protected access modifier is similar to that of private access modifiers, the difference is that the class member declared as Protected are inaccessible outside the class but they can be accessed by any subclass(derived class) of that class.

Output -

Class Members

There are two members of a class namely Data Members and Member Functions. "Data Member" and "Member Functions" are the new names/terms for the members of a class, which are introduced in C++ programming language.
The variables which are declared in any class by using any fundamental data types (like int, char, float etc) or derived data type (like class, structure, pointer etc.) are known as Data Members. And the functions which are declared either in private section of public section are known as Member functions.
Example -

In the above example, 
Data Members are- int no and char name[30].
Data Functions are- void getinfo(); and void showinfo();

Non-Member Functions

There are two main differences between Member Functions and Non-member functions.
  1. A non-member function always appears outside of a class. Whereas a member function may or may not appear outside.
  2. Method of function call is different for calling member functions and non-member functions.
In simple words, non-member functions are nothing but the regular or simple functions.
Example - 

Defining a member function

A member function can be defined in two ways-
  1. Inside the class :
  2. Outside the class :

Inline Function

C++ inline function is powerful concept that is commonly used with classes. If a function is inline, the compiler places a copy of the code of that function at each point where the function is called at compile time.
To inline a function, place the keyword inline before the function name and define the function before any calls are made to the function. The compiler can ignore the inline qualifier in case defined function is more than a line.
A function definition in a class definition is an inline function definition, even without the use of the inline specifier.
Syntax - inline return_type function_name(arg 1, arg 2,..., arg n);
Example -

Static Data Members

We can define class members static using static keyword. There are few characteristics of a static data member -
  1. Static Data Member is initialized to zero when the first object of its class is created. No other initialization is permitted.
  2. Only one copy of that member is created for the entire class and is shared by all the objects of that class, no matter how many objects are created.
  3. It is visible only within the class, but its lifetime is the entire program. (similar to the global variables)
Syntax - static data_type variable_name;
Example -
Output -

Static Member Functions

Just like static member variable, we can also have static member functions. A member function that is declared static has the following properties -
  1. A static function can have access to only other static members (functions or variables) declared in the same class.
  2. A static member function can be called using the class_name (instead of its object_name) as follows -
    syntaxclass_name :: function_name(argument);
Example -
Output -

Pointer to object

A pointer can point to an object created by a class. Consider following statement :
item x;
where item is a class and x is an object defined to be of type item. Similarly we can define a pointer it_ptr of type item as follows :
item *it_ptr;
Object pointers are useful in creating objects at run time. We can also use an object pointer to access the public members of an object. Consider a class item defined as follows:
Let us declare an item variable x and a pointer ptr to x as follows:
The pointer ptr is initialized with the address of x.
We can refer to functions of item in two ways :
  1. By using the dot (.) operator and the object -
    x.getdata(100,75.50);
    x.show();
  2. By using arrow operator (->) and the object pointer -
    ptr -> getdata(100,75.50);
    ptr -> show();
  3. Using (*ptr) in place of x -
    (*ptr).getdata(100,75.50);
    (*ptr).show();
Example -
Output-

Array of objects

We can declare an array of a class variable. Such arrays are called array of objects.
Example -

Passing objects as arguments

Like any other data-type, an object may be used as a function argument. This can be done in two ways -

  1. A copy of the entire object is passed to the function.
  2. Only the address of the object is transferred to the function.
Example -
Output -

Dynamic Memory Allocation

'C' uses malloc( ) and calloc( ) functions to allocate memory dynamically at run-time. Similarly, it uses the function free( ) to free dynamically allocated memory. We use dynamic allocation techniques when it is not known in advance how much of memory space is needed. Although C++ supports these functions, it also defines two unary operators new and delete that perform the task of allocating and freeing the memory in better and easier way. Since these operators manipulate memory on the free store, they are also known as free store operators.

  • The new operator is used to create objects of any type. It takes the following general form -
    Syntax :
    pointer_variable = new data_type;
    p=new int;
    q=new float;
  • The delete operator is used to de-allocate the memory created by the new operator at run time. Once the memory is no longer needed, it should be freed so that the memory becomes available again for other requests of dynamic memory.
    Syntax :
    delete ptr;  //de-allocate memory for one element
    delete[] ptr;  //de-allocate memory for array
Example to illustrate the use of new and delete operator -
Output -

Friend Function

Private members of any class are accessed only within the class they are declared. Friend function is used to access the private and protected members of different classes. It works as a bridge between classes.
Rules/Characteristics -
  1. Friend function must be declared with friend keyword.
  2. Friend function must be declared in all the classes from which we need to access private or protected members.
  3. Friend function must be defined outside the class without specifying the class name.
  4. Friend function will be invoked like a normal function without any object. (Global scope)
  5. Friend function has objects as arguments.
Q. Write an OOP to find the largest number between two different classes' object data members.
Ans.

Output -

Friend Class

Like friend function, a class can also be a friend of another class. A friend class can access all the private and protected members of other class.
In order to access the private and protected members of a class into friend class we must pass on the object of a class to the member functions of friend class.
Example -
In the above example, we have created two classes Rectangle and Square. Using statement 1 we have made Square class, a friend class of Rectangle class. In order to access the private and protected members of Rectangle class into Square class, we must explicitly pass an object of Rectangle class to the member functions of Square class as shown in statement 2.
This is similar to passing an object as a function argument but the difference is, an object (R) we are passing as an argument is of a different class (Rectangle) and the calling object is of a different class (Square).
Output -

Nested classes

A nested class is a class that is declared in another class. The nested class is also a member variable of the enclosing class and has the same access rights as the other members. However, the member functions of the enclosing class have no special access to the members of a nested class.
Example - 

Output -

Constructor

A constructor is a special member function whose task is to initialize the objects of its class. It is special because its name is the same as the class name. The constructor is invoked whenever an object of its associated class is created. It is called constructor because it constructs the values of data members of the class.
Declaration & Definition -
Characteristics of a constructor -
  • They should be declared in the public section.
  • They are invoked automatically when the objects are created.
  • They do not have return types, not even void and therefore, they cannot return values.
  • They cannot be inherited, though a derived class can call the base class constructor.
  • Like other C++ functions, they can have default arguments.
  • Constructors cannot be virtual.
  • We cannot refer to their addresses.
  • An object with a constructor cannot be used as a member of union.
  • They make implicit calls to the operators new and delete when memory allocation is required.
Note - When a constructor is declared for a class, the initialization of the class objects becomes mandatory.
Example -
Default Constructor
Output -

Types of constructor

1. Default Constructor (Constructor with no arguments) :

A constructor that accepts no parameters is known as Default Constructor. For example,
The default constructor of class A is -  A::A()
If no such constructor is defined, then the compiler supplies a default constructor.
A statement such as - 
A obj ;
invokes the default constructor of the compiler to create the object obj.
Syntax -
The example of the default constructor is shown previously.

2. Parameterized Constructor (Constructor with arguments) :

The constructors that can take arguments/parameters are called Parameterized Constructors.
Syntax -
We pass arguments to the constructor function in 2 ways-
  • By calling the constructor explicitly.
  • By calling the constructor implicitly.
Example -
Output -

3. Copy Constructor :

The copy constructor creates an object by initializing it with an object of the same class, which has been created previously. It is used to -
  • Initialize one object from another object of the same class.
  • Copy an object to pass it as an argument to a function.
  • Copy and object to return it from a function.
Syntax -
Example -

Output -

Constructor Overloading

In C++, we can have more than one constructor in a class with the same name, as long as each has a different list of arguments. This concept is known as constructor overloading and it is quite similar to function overloading.
Overloaded constructors essentially have the same name(name of the class) and different number of arguments.
A constructor is called depending upon the number and type of arguments passed.
Example -
Output -

Destructor

In C++, a destructor is a special member function that is executed automatically when an object is destroyed that has been created by constructor.
C++ destructors are used to de-allocate the memory that has been allocated for the object by the constructor.
Syntax of destructor is same as the constructor except that it is preceded by the tilde (~) sign.
Syntax -
Unlike constructor, a destructor neither takes any arguments nor does return value. 
Destructors can't be overloaded.
Example -
Output -

Operator Overloading

An operator is a symbol that tells the compiler to perform a specific task. Operators have their own personalities to work with built-in data types. Class is user-defined data type and the compiler doesn't understand how to use operators with user-defined data types. To use operators with user-defined data types, they need to be overloaded according to a programmer's requirement.
Operator overloading is a way of providing a new implementation of existing operators to work with user-defined data types.
An operator can be overloaded by defining a function to it. The function for operator is declared by using the operator keyword followed by the operator symbol.
We can overload all the C++ operators except the following -
  1. Class member access operators (.,.*)
  2. Scope resolution operator (::)
  3. Size operator (sizeof)
  4. Conditional operator (?:)
There are two types of operator overloadings in C++ :
  • Unary Operator Overloading
  • Binary Operator Overloading

Unary Operator Overloading :

Let us overload unary minus operator (-)  
Example -
Output -

Binary Operator Overloading :

Example -
Output -

Operator Overloading using friend function

Syntax
Example -
Output -

Type conversion

Converting data from one type to another type is known as type conversion.

Types of type conversion :

  1. Conversion from basic type to basic type.
  2. Conversion from basic type to class type.
  3. Conversion from class type to basic type.
  4. Conversion from class type to class type.

1. Conversion from basic type to basic type :

There are two types in this conversion -
  • Implicit (Automatic)
  • Explicit (By programmer)
Implicit type conversion -
This type of conversion is done by the C++ compiler from the type that doesn't fit to the type it wants.
Example -
Here, the value 3.1416 will be converted into integer type i.e., 3 and stored into variable m.
Explicit type conversion -
This type of conversion is done by the programmer from the type that doesn't fit into the type he wants.
Example -
Here, m will be converted into float value 3.0 explicitly using float(m) and float value 1.5 will be stored in variable x.

2. Conversion from basic type to class type :

In C++, the conversion of basic type to class type can be done using constructors.
Example -

3. Conversion from class type to basic type :

In C++, the conversion from class type to basic type can be done by using overloaded casting operator. It is also known as conversion function.
Syntax -
Casting operator function should satisfy the following conditions -
  • It must be a class member.
  • It must not specify the return type.
  • It must not have any arguments.
Example -

4. Conversion from class type to class type :

objX = objY
Data of type class Y is converted into data of type X and converted value is assigned to objX. Since conversion takes place from class Y to class XY is source class and X is known as destination class. There are two ways to convert class type to class type -
  • Using casting operator in source class.
    Example -
  • Using constructor conversion in destination class.
    Example -
For both of the types above, we have to use following code in function main()

Comments

Popular posts from this blog

Introduction to OOP (Object Oriented Programming)