Showing posts sorted by relevance for query Classes. Sort by date Show all posts

Features Of OOPS-Inheritance in C++

Inheritance in C++

The process of obtaining the data members and methods from one class to another class is known as inheritance. It is one of the fundamental features of object-oriented programming.

Important points

  • In the inheritance the class which is give data members and methods is known as base or super or parent class.
  • The class which is taking the data members and methods is known as sub or derived or child class.

Syntax

class subclass_name : superclass_name  
{  
    // data members
   // methods  
}  

Real Life Example of Inheritance in C++

The real life example of inheritance is child and parents, all the properties of father are inherited by his son.
real life example of inheritance in c++

Diagram

inheritance in C++
In the above diagram data members and methods are represented in broken line are inherited from faculty class and they are visible in student class logically.

Advantage of inheritance

If we develop any application using this concept than that application have following advantages,
  • Application development time is less.
  • Application take less memory.
  • Application execution time is less.
  • Application performance is enhance (improved).
  • Redundancy (repetition) of the code is reduced or minimized so that we get consistence results and less storage cost.

Tpyes of Inheritance

Based on number of ways inheriting the feature of base class into derived class it have five types they are:
  • Single inheritance
  • Multiple inheritance
  • Hierarchical inheritance
  • Multiple inheritance
  • Hybrid inheritance

Single inheritance

In single inheritance there exists single base class and single derived class.
single inheritance

Multiple inheritances

In multiple inheritances there exists single base class, single derived class and multiple intermediate base classes.
Single base class + single derived class + multiple intermediate base classes.

Intermediate base classes

An intermediate base class is one in one context with access derived class and in another context same class access base class.
multilevel inheritance
Hence all the above three inheritance types are supported by both classes and interfaces.

Multiple inheritance

In multiple inheritance there exist multiple classes and singel derived class.
multiple inheritance

Hybrid inheritance

Combination of any inheritance type
hybrid inheritance

Inheriting the feature from base class to derived class

In order to inherit the feature of base class into derived class we use the following syntax

Syntax

class classname-2 : classname-1
{
variable  declaration;
method declaration;
}

Explanation

  • classname-1 and classname-2 represents name of the base and derived classes respectively.
  • is operator which is used for inheriting the features of base class into derived class it improves the functionality of derived class.

Example of Inheritance in C++

#include<iostream.h>
#include<conio.h>

class employee
{
public:
int salary;
};
class developer : public employee
{
employee e;
public:
void salary()
{
cout<<"Enter employee salary: ";
cin>>e.salary;   // access base class data member
cout<<"Employee salary: "<<e.salary;
}
};

void main()
{
clrscr();
developer obj;
obj.salary();
getch();
}

Output

Enter employee salary: 50000
Employee salary: 50000

Storage Classes in C

Storage Classes in C

#Storage class specifiers in C language tells to the compiler where to store a variable (Storage area of variable), how to store the variable, Scope of variable, Default value of a variable (if it is not initialized it), what is the initial value of the variable and life time of the variable.
Storage classes of C will provides following information to compiler.
  • Storage area of variable
  • Scope of variable that is in which block the variable is visible.
  • Life time of a variable that is how long the variable will be there in active mode.
  • Default value of a variable if it is not initialized it.

Type of Storage Class

Storage classes in mainly divided into four types,
  • auto
  • extern
  • static
  • register

Properties of All storage class

TypeStorage placeScopeLifeDefault Value
autoCPU MemorybodyWithin the FunctionGarbage value
staticCPU Memoryfunctionprogram0 (zero)
externCPU MemoryprogramTill the end of the main program.0 (zero)
registerRegister memorybodyWithin the FunctionGarbage value

auto Storage Class

The auto storage class is the default storage class for all local variables. The scope auto variable is within the function. It is equivalent to local variable.

Syntax

{
   int roll;
   auto int roll;
}
In above example define two variable with same storage class auto and their scope is within the function.

Example of auto storage class

#include<stdio.h>
#include<conio.h>

void increment();
void main()
{
increment();
increment();
increment();
increment();
getch();
}
void increment()
{
auto int i = 0 ;
printf ( "%d", i ) ;
i++;
}

Output

Output:
0 0 0 0

static Storage Class

The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope.

Example of static storage class

#include<stdio.h>
#include<conio.h>

void increment();
void main()
{
increment();
increment();
increment();
increment();
getch();
}
void increment()
{
static int i = 0 ;
printf ("%d", i ) ;
i++;
}

Output

Output:
0 1 2 3

extern Storage Class

The extern storage class is used to give a reference of a global variable that is visible to ALL the program files. It is equivalent to global variable.

Example of extern storage class

Example

#include<stdio.h>
#include<conio.h>

int x = 20 ;
void main( )
{
extern int y;
printf("The value of x is %d \n",x);
printf("The value of y is %d",y);
getch();
}
int y=30;

Output

The value of x is 20
The value of y is 30

Register variable

Register variables are also local variables, but stored in register memory. Whereas, auto variables are stored in main CPU memory.
Advantages: The register variables are faster than remaining variables, because register variable are stored in register memory not in main memory..
Limitation: But, only limited variables can be used as register since register size is very low. (16 bits, 32 bits or 64 bits).
  • In TC-3.0 we can't access the address of register variables.
  • Pointer are ptr related concepts are can't applied to register variable.

Example

void main()
{
register int a=10;
++a;
printf("\n value of a: %d",a);
printf("Enter a value:");
scanf("%d",&a);
--a;
printf("\n value of a: %d",a);
getch();
}

Output

Input data is 50.
Error, must take address of a memory location.

Explanation

  • In scanf() function if address is provided for the register variable then it will give error, if addition is not provided it normally work.
  • Register storage class specifier just recommended to the compiler to hold the variable in CPU register if the memory is available or else stored in stack area of data segment.

Classes and Objects

Classes and Objects

C++ Class

  • Before you create an object in C++, you need to define a class.
  • A class is a blueprint for the object.
  • We can think of class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows etc. Based on these descriptions we build the house. House is the object.
  • As, many houses can be made from the same description, we can create many objects from a class.


How to define a class in C++?

  • 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.

class className
   {
   // some data
   // some functions
   };

Example: Class in C++

class Test
{
    private:
        int data1;
        float data2;  

    public:  
        void function1()
        {   data1 = 2;  } 

        float function2()
        { 
            data2 = 3.5;
            return data2;
        }
   };
  • Here, we defined a class named Test.
  • This class has two data members: data1 and data2 and two member functions: function1() and function2().


Keywords: private and public

You may have noticed two keywords: private and public in the above example.
  • The private keyword makes data and functions private. Private data and functions can be accessed only from inside the same class.
  • The public keyword makes data and functions public. Public data and functions can be accessed out of the class.

Here, data1 and data2 are private members where as function1() and function2() are public members.
If you try to access private data from outside of the class, compiler throws error. This feature in OOP is known as data hiding.

C++ Objects

  • When 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 to Define Object in C++

className objectVariableName;
  • You can create objects of Test class (defined in above example) as follows:


class Test
{
    private:
        int data1;
        float data2;  

    public:  
        void function1()
        {   data1 = 2;  } 

        float function2()
        { 
            data2 = 3.5;
            return data2;
        }
   };

int main()
{
    Test o1, o2;
}
Here, two objects o1 and o2 of Test class are created.
In the above class Testdata1 and data2 are data members and function1() and function2() are member functions.

How to access data member and member function in C++?

  • You can access the data members and member functions by using a . (dot) operator. For example,

o2.function1();
This will call the function1() function inside the Test class for objects o2.
Similarly, the data member can be accessed as:
o1.data2 = 5.5;
It is important to note that, the private members can be accessed only from inside the class.
So, you can use o2.function1(); from any function or class in the above example. However, the code o1.data2 = 5.5; should always be inside the class Test.

Example: Object and Class in C++ Programming

// Program to illustrate the working of objects and class in C++ Programming
#include <iostream.h>
#include<conio.h>

class Test
{
    private:
        int data1;
        float data2;

    public:
       
       void insertIntegerData(int d)
       {
          data1 = d;
          cout << "Number: " << data1;
        }

       float insertFloatData()
       {
           cout << "\nEnter data: ";
           cin >> data2;
           return data2;
        }
};

 int main()
 {
      Test o1, o2;
      float secondDataOfObject2;

      o1.insertIntegerData(12);
      secondDataOfObject2 = o2.insertFloatData();

      cout << "You entered " << secondDataOfObject2;
      return 0;
 }
Output
Number: 12
Enter data: 23.3
You entered 23.3
  • In this program, two data members data1 and data2 and two member functions insertIntegerData() and insertFloatData() are defined under Test class.

Two objects o1 and o2 of the same class are declared.
The insertIntegerData() function is called for the o1 object using:
o1.insertIntegerData(12);
  • This sets the value of data1 for object o1 to 12.

Then, the insertFloatData() function for object o2 is called and the return value from the function is stored in variable secondDataOfObject2 using:
secondDataOfObject2 = o2.insertFloatData();
In this program, data2 of o1 and data1 of o2 are not used and contains garbage value.