Showing posts with label CPP Programming & Concepts. Show all posts
Showing posts with label CPP Programming & Concepts. Show all posts

Inheritance | C++

Inheritance in C++


Re-usability is one of the important feature in OOPs that we can achieve by inheritance. It is a concept of derived class and Base class.
It is the mechanism of deriving new class from old class is called inheritance.
Here the old class is called derived class and new class is called derived class.
The derived class inherit some or all the properties of the base class.A class can also inherit the properties of more than one class or more than one level.

Derived Class


Derived class is define by specifying its relationship with the base class in addition to its own details. The general form of defining derived class is
class derived class-name : visibility mode base class-name
{
members of derived class;
}

Here the (:) colon indicate that derived class-name is derived from its base class-name. The visibility mode is optional and if present may be either private or public. The default visibility mode is private visibility mode specifies whether the feature of base class are privately or publically derived.

On the basis of accessibility


There are three type of accessibility
  1. Private
  2. Public
  3. Protected

Example

class base
{
members of base
};
CASE I:
class derived-1 : public base
{
members of derived-1 + Public member of base and protected member of base
};
CASE II:
class derived-2 : protected base
{
members of derived-2 + public and protected member of base
};
CASE III:
class derived-3 : private base
{
members of derived-3 + public and protected member of base
};

Let we discuss about the cases


Case I : When base class is inherited publicaly by derived 1 class than.


  • public member of base class are inherited as a public.
  • private member of base class are not accessable.
  • protected member of base class are inherited as a protected.

Case II : When base class is inherited as a protected by derived 2 class than.


  • public member of base class are inherited as a protected.
  • private member of base class are not inherited.
  • protected member of base class are inherited as a protected.
so in derived 2 class members will be:
public :
int a2;
protected :
int c2 , x , z;
int b2;

Case III : When base class is inherited as a private by derived 3 class than.


  • public member of base class are inherited as a private.
  • private member of base class are not inherited.
  • protected member of base class are inherited as a private.
so in derived 3 class members will be:
public :
int a3;
protected :
int c3;
int b2,x,z;

Type of inheritance


  1. Based on structure of inheritance
  2. Based on accessibility of inheritance

Based on structure of inheritance


  1. Simple inheritance or single inheritance
  2. Multilevel inheritance
  3. Hierarchical inheritance
  4. Multiple inheritance
  5. Hybrid inheritance

Single inheritance


A derived class with only one base class is called single inheritance

Example


Copy Code
#include <iostream>

using namespace std;
class person //base class
{
    string name;
    string add;

public:
person()
{
    name='\0';
    add='\0';
}
person(string n)
{
    name=n;
    add='\0';
}
person(string n,string a)
{
    name=n;
    add=a;
}
void read()
{
    cout<<"Enter name:";
    cin>>name;
    cout<<"Enter address:";
    cin>>add;
}
void print()
{
    cout<<"Name="<<name<<"\n";
    cout<<"Address="<<add<<"\n";
}
};

class stud:public person
{
    string scno;
    int marks;
    public:
    stud()
    {
        scno='\0';
        marks=0;
    }
    stud(string s)
    {
        scno=s;
        marks=0;
    }
    stud(string s,int m)
    {
        scno=s;
        marks=m;
    }
    void read()
    {
        person::read();
        cout<<"Enter scno:";
        cin>>scno;
        cout<<"Enter marks:";
        cin>>marks;
    }
    void print()
    {
        person::print();
        cout<<"SCNO="<<scno<<"\n";
        cout<<"Marks:"<<marks;
    }
};

int main()
{
    stud st;
    st.read();
    st.print();

    return 0;
}

Output

Enter name:shailu
Enter address:bhopal
Enter scno:23
Enter marks:60
Name=shailu
Address=bhopal
SCNO=23
Marks:60

Multilevel inheritance


The mechanism of deriving a class from another derived class is called multilevel inheritance

Hierarchical inheritance


One class may be inherited by more than one derived class is called hierarchical inheritance.

Multiple inheritance


One derived class with several base class is called multiple inheritance.

Hybrid inheritance


Combination of one or more above inheritance is called hybrid inheritance.
code

Type Conversion | C++

Type Conversion in C++


There are type of situation arise in data conversion between uncompatable type.
  1. Type I : Conversion from built in type (BDT-basic data type) to built in type (BDT-basic data type)
  2. Type II : Conversion from built in type (BDT-basic data type) to class type (UDT-user define data type)
  3. Type III : Conversion from class type (UDT-user define data type) to built in type (BDT-basic data type)
  4. Type IV : Conversion from class type (UDT-user define data type) to class type (UDT-user define data type)

Type I : Conversion from built in type (BDT-basic data type) to built in type (BDT-basic data type)


This type of conversion is done automatically.

Type II : Conversion from built in type (BDT-basic data type) to class type (UDT-user define data type)


Here if we want to convert BDT to UDT than some additional overloaded conversion function takes place in destination class. such as:
 
operator int()  
    {              
       return(a); 
    }

Example

Copy Code
#include <iostream>

using namespace std;
class source
{
    int a;
    public:
    source()
    {
        a=0;
    }
    source(int x)
    {
        a=x;
    }
    
    operator int() // for type conversion obj s1= int r; in main here int is converted into source  
    {              // for BDT to UDT 
       return(a); 
    }
    
    ~source(){ }
};


int main()
{
   source s1; 
   int r=10;
   s1=r; 
   cout<<s1;
   return 0;
}

Output:

10


Type III : Conversion from class type (UDT-user define data type) to built in type (BDT-basic data type)


Here if we want to convert BDT to UDT than some additional overloaded conversion function takes place in source class. such as:

operator int()  
    {              
       return(a); 
    }

Example

Copy Code
#include <iostream>

using namespace std;
class source
{
    int a;
    public:
    source()
    {
        a=0;
    }
    source(int x)
    {
        a=x;
    }
    
    operator int() // for type conversion  int r= s1 (object) in main here source is converted into int
    {              // for UDT to BDT conversion
       return(a); 
    }
    int geta()
    {
        return(a);
    }
    
      ~source(){ }
};


int main()
{
  source s1;
  int r=s1;
  cout<<s1;
  return 0;
}

Output:

0

Type IV : Conversion from class type (UDT-user define data type) to class type (UDT-user define data type)


Case I: For d = s

If source is the source class and dest is the destination class than
We can write d = s in main() after adding some conversion function in source class and overload conversion function in destination class such as
In Source class function is
 
int geta()
    {
        return(a);
    }

In destination class overload function is
 
dest (source obj)
    {
        p=obj.geta();
    }
Note:This overloaded conversion function is used when we want to access the private data member of source class indirectly.
Indirectly means we can not access private data member of source class. So we access conversion function of source class which is define in source class.
It must be noted that those class which define first is called source class like source and dest class is define after source class so it is a destination class.

Example

Copy Code
#include <iostream>
using namespace std;

class source
{
    int a;
    public:
    source()
    {
        a=0;
    }
    source(int x)
    {
        a=x;
    }
        
    int geta()
    {
        return(a);
    }
     
    ~source(){ }
};

class dest
{
    int p;
    public:
    dest()
    {
        p=0;
    }
    dest(int x)
    {
        p=x;
    }
    operator int()  
    {              
       return(p); 
    }
    
    dest (source obj)
    {
        p=obj.geta();
    }
    
    ~dest(){ }
};


int main()
{
  source s1;
  dest d1;
  d1=s1; // convert from s1 (source type) to d1(dest type)
  cout<<d1;
  return 0;
}

Output:

0

Case II: For s = d

If the source class is dest and destination class is source than conversion function in source class and overload conversion function in destination class will be
In Source class function is
 
int getp()
    {
        return(p);
    }

In destination class overload function is
 
dest (source obj)
    {
        a=obj.getp();
    }

Output:

0

Example

Copy Code
#include <iostream>
using namespace std;


class dest
{
    int p;
    public:
    dest()
    {
        p=0;
    }
    dest(int x)
    {
        p=x;
    }
    
    int getp()
    {
        return(p);
    } 
    
    ~dest(){ }
};

class source
{
    int a;
    public:
    source()
    {
        a=0;
    }
    source(int x)
    {
        a=x;
    }
    operator int()
    {
        return(a);
    }
    
    source (dest obj)
    {
        a=obj.getp();
    }
    ~source(){ }
};

int main()
{
  source s1;
  dest d1;
  s1=d1; // convert from d1 (source type) to s1(dest type)
  cout<<s1;
  return 0;
}

Output:

0

Constructors and Destructor in C++

Constructors & Destructor in C++

Constructors


A constructor is a special member function whose task is to initialize the object of its class. It is special because its name is the same as the class name. The constructor is call whenever an object of its associated class is created. It is called constructor because it construct the value of data member of class. Constructor must follow following properties.

Properties


  1. Name of constructor is same as the class name.
  2. Constructor will call implicitly at the time of declaration.
  3. Constructor does not have any return type.
  4. Constructor are used to define object that mean to initialize member data.
  5. Constructor must be a public member function of a class. If constructor is private then user is unable to create object of such class.
  6. Constructor can be overload that means more than one constructor is possible in a class.
  7. We can not refer their address.

Type of Constructors


  1. Parameterized Constructor
  2. Default Argument Constructor such as
  3. Copy Constructor

Parameterized Constructor


The constructor that can take argument is called parameterized constructor.
Example:
Copy Code
#include <iostream>

using namespace std;
class add
{
    int a,b;
    public:
    add(); 
    add(int);
    add(int,int);
    void print();
};
add::add()
{
    a=2;
    b=5;
}
add::add(int x)
{
    a=x;
    b=x;
}
add::add(int x,int y)
{
    a=x;
    b=y;
}
void add::print()
{
    cout<<"\n"<<"a="<<a<<"\n"<<"b="<<b<<"\n"<<"Sum="<<a+b<<"\n";
}
int main()
{
    add a1;
    a1.print();
    add a2(10);
    a2.print();
    add a3(10,20);
    a3.print();

    return 0;
}

In the above example show how to use zero argument ,one argument,two argument constructor in any program.

Output

a=2
b=5
Sum=7

a=10
b=10
Sum=20

a=10
b=20
Sum=30

Default Argument Constructor


It is possible to define constructor with default arguments.

Example:


Add(int x,int y=0);
Here the default value of y is 0.

If the statement is Add A1(10);
That means assign the value 10 for x and 0 for y by default.

If the statement is Add A1(10,20);
That means assign 10 for x and 20 fro y. The actual parameter when specified overrides the default value.

Note: It is most important to distinguish between the default constructor Add::Add() and the default argument constructor Add::Add(int=0).The default argument can be called with either by one argument or no argument.When called with no argument it become default constructor.

Example:


Copy Code
#include <iostream>

using namespace std;
class add
{
    int a,b;
    public:
    add(); 
    //add(int);
    add(int,int=0); //Default Argument Constructor
    void print();
};
add::add()
{
    a=2;
    b=5;
}

add::add(int x,int y)
{
    a=x;
    b=y;
}
void add::print()
{
    cout<<"\n"<<"a="<<a<<"\n"<<"b="<<b<<"\n"<<"Sum="<<a+b<<"\n";
}
int main()
{
    add a1;
    a1.print();
    add a2(10);
    a2.print();
    add a3(10,20);
    a3.print();

    return 0;
}

Output

a=2
b=5
Sum=7

a=10
b=0
Sum=10

a=10
b=20
Sum=30

Copy Constructor


It is used to define constructor function which is used to initialize a new object with the help of object of same class in other words copy constructor is a constructor which take a object of same class as an argument.Copy constructor override the process of copy initilization.

Example:


Copy Code
#include <iostream>
using namespace std;
class add
{
    int a,b;
    public:
    add();
    add(int);
    add(int,int);
    add(add &);  // Declare Copy Constructor
    void print()
    {
        cout<<"\n"<<"a="<<a<<"b="<<b<<"\n";
    }
};
add::add(add &x)  // Definition of Copy Constructor
    {
        a=x.a;
        b=x.b;
    }
add::add()
{
    a=0;
    b=0;
}
add::add(int s)
{
    a=s;
    b=s;
}
add::add(int p,int q)
{
    a=p;
    b=q;
}

int main()
{
   add A1;
   add A2(10);
   add A4(10,20);
   add A5=A4; //Call copy constructor implicitly 
   A5.print();
   add A6=A1;  //Call copy constructor implicitly 
   A6.print();
   add A7=A2;  //Call copy constructor implicitly 
   A7.print();
   
    return 0;
}

Output

a=10 b=20
a=0 b=0
a=10 b=10

Destructor


A destructor is used to destroy the object that have been created by the constructor Like a constructor the destructor is a member function whose name is the same as the class name but is preceded by a tilde (~)
A destructor never takes any argument nor does it return any value.It will be called by compiler to cleanup strong that are no longer accessible. It is good practice to declare destructor in a program since it release memory space for future use.

Example:

~Add()
{
cout<<"Iam Destructor";
}

Properties of OOPs | C++

Properties and characteristics of OOPs

Obect Oriented Programming is a Programming methodology which implement the concept of modules with essential properties. Modules means the idea of structured programming. Module encourage the decomposition of any problem in possible sub problems.The language which follow the concept of OOPs is known as Object Oriented Programming Language such as C++,C#,Java etc.

Properties or Characteristics of OOPs

Let we discuss about the properties of Object Oriented Programming Language such as:

  1. Data Abstraction
  2. Encapculation
  3. Inheritance
  4. Polymorphism

Data Abstraction

It is a concept by which can represent any object by its essential fearure only without getting inner details.
In real world we represent any person by its name , instead of giving all information about him.

Encapculation

Process of wrapping of data and function or procedure into single unit is known as encapsulation.
So data encapsulation, we can protect (insulate) data from direct access by any external functionthat is known as data hiding.In prcedural programming accedental use of data was really a big problem that is solved by using the concept of data abstraction and encapsulation.

Inheritance

Inheritance means to acquire the properties from others.In real life we commonly use the concept of classification hierarchy.OOPs supports classification concept in the form of inheritance.
"Inheritance is a process by which object of one class can acquaire the properties or attributes of another class"
The object by which properties are accessed form base class and received by derived class.

Polymorphism

"One interface multiple method"
In real life a particular thing can be use in different manner according to different situation or condition for example a person role is different at different place.
Ploymorphism means the ability to take more than one form.In C++ concept of polymorphism is implemented using function overloading.

INDEX | Programming in C++

FUNCTION OVERLOADING AND OPERATOR OVERLOADING IN C++

📌Highlights: Hello Friends! In this post we discuss about Overloading concept in C++. We cover following topics such as Function Overloading, Operator Overloading, concept of polymorphism, Examples.

OVERLOADING: When we use same thing for different purpose than it is known as overloading.

What is Inline Function in CPP




Now In this article I am going to explain about Inline Function in C++. also explain in such a way that you are able to understand and answer the following questions that arise in your mind  💧What is Inline function ? 💧Why it is useful in C++ programming? 💧When it is used? 💧 How it is used?

Inline Function:

It is an important feature of C++ programming. As the name says Inline function that means it is a function followed by keyword  Inline. Some time we need to call any function many times in a program than Inline function is useful.But if our function have number of line of code or simply we can say that function is big in size than it will take lot of time for compiling each line of code and if we call again and again a lot of memory is wastage. Most of the time it busy for performing following tasks such as 💧 jumping to the function.💧 Saving registers💧 Pushing argument into the stack and return to calling function. 

So we can say that it take lot of extra time for executing the instructions and perform above tasks. 

So, to eliminate the cost of calls to small function, C++ propose a new feature called Inline Function.
Inline function that replace the call with their definitions at the time of compilation.It is just like a macro in C

Syntax:

Inline function_header

{
    function body;

Example :

inline void show()
{
    cout <<"Inline Function";
}

void main()
{
    show();
    show();
    show();
    show();
}

Explanation :

Here inline function replace f() by cout <<"Inline Function" at compilation time.Here time is saved but memory space is waste.
All inline function must be define before they are called. If the function is large in size then inline function work in slower speed. It is beneficial in small function which is written in one or two lines. 

Example:

#include <iostream.h>
#include <conio.h>
inline float mul(float a, float b)
{
    return (a * b);
}
inline double div(double x, double y)
{
    return (x / y);
}
main()
{
    float p=12.345;
    float q=9.82;
    cout << mul (p , q)<<"\n";
    cout << div ( p , q)<<"\n";
}

Note: When we are using inline function then there are some restriction that have to be in mind such as Any inline function doesn't have any looping statements inside inline function.
Any inline function doesn't have any if-else statements inside inline function.
Any inline function doesn't have any break statements inside inline function.
Any inline function doesn't have any continue statements inside inline function.
Any inline function doesn't have any goto statements inside inline function.
Any inline function doesn't have any switch statements inside inline function.

So, we can say that it is a function contain simple statements.

Data Encapsulation



Encapsulation  is one of the characteristic of OOPs. Encapsulation is a process of wrapping of data into single unit or block. Data may be data type or functions. By encapsulation we can protect data from direct access by any external method. In encapsulation part of data inside block is called member data and function inside the block is called member function. We can access member data and member function by using access specifiers such as Public or Private or Protected. 

Data Abstraction | CPP



Its is one of the characteristics of OOP. It is a concept by which we can represent any object by it essential features only without getting inner details. By this concept inner information is hidden from end users. Users don't know about the internal mechanism of any object. Some time we interact to any object without knowing their complete information , just like in real world we represent any person by its name instead of giving all details about that person.  

Friends !  For understanding Data Abstraction first you link our self to real world don't see it technically than you can understand easily.

Data Abstraction Simple Means Data Hiding

Now first we see ,  Is it happen in our real life ? yes so many times. just remember 

some time you ask to your mother to make some testy food , she make and serve you , you eat and say wow what a food it is very testy with out knowing their internal ingredients used  and procedure to make that food. That all thing are hidden for you.

When you are purchase some appliances you just use it without knowing their internal mechanism. All internal mechanism and parts are covered by some substance so we can not see it. It is hidden for us.

Some time when you know any person by name without knowing their inner detail such as family detail , their occupation etc.

So I just try to say it is simple concept of hiding things from end user. Don't take it in complicated way.

Now come in technical terms in C++ how it happen and how it is implemented.

I hope you all know about objects in brief every thing in real world is objects which have some properties.

So we can say that "Data Abstraction is a concept by which we can represent any object by it's important features only without knowing their inner details"

In C++ we can achieve data abstraction using classes , Header files & Predefined functions

➤ Class contain all data member and data function in single unit.

Note: We can only access that data members and functions by using access specifiers in C++. Access specifiers may be private or public. Private means it is accessible inside the block and public means it is accessible from any where inside the program.

#include <iostream>    
 using namespace std;    
 class Add    
{    
   private: int a, b, c; // private variables  
   public:    
   void addition()    
{    
   cout<<"Enter two numbers: ";    
   cin>>a>>a;    
   c= a+a;    
   cout<<"Addition of two number is: "<<c<<endl;    
}    
};    

int main()    
{    
  Add ad;    
  ad.addition();    
  return 0;    
}    


➤ Header files & Predefined functions are also example of data Abstraction because in case we only use function like pow() , abs() , exp() etc. with knowing internal functionality or mechanism or algorithm.

Header Files such as : <cmath> , <cctype> , <cstdlib> , <ctime> , <csignal> etc.

#include <iostream>  
#include<math.h>  
using namespace std;  
int main()  
{    
   int a = 3;  
   int b= 2;  
   int c = pow(a , b);         // pow( a , b ) is the  power function  
   cout << "Square of a is : " <<c<< endl;  
   return 0;  
}  

Calling Method Definition & implementation in C++



Calling method is an important phenomenon in programming. There are different calling methods in different programming language. But here we discuss about C++. Before discuss about calling method in C++  we will take one review of calling method in C. In C we can call method by using call by value and call by pointer. In C++ we can call method by using call by value and call by reference. In this post we will both method in detail and also differentiate between call by pointer and call by reference.