Friend function in c plus plus

Friend function in c plus plus

The problem with class is that we cannot access private and protected members out side the class i-e in main().

Example program


#include<iostream.h>

class A

{

private:

void show()

{

cout<<"Trustingeeks.com"<<endl;

}

};

main()

{

A obj;

obj.show();

}

Output

Friend function

 

Also we saw in inheritance one class inherits members (protected, public) of another class. BUT the problem that in inheritance private members cannot be inherited.

For example in every day life child can use all the things of parent except private things. Same is case with inheritance in C++. But one friend can use all things including private things of another things.

Inheritance in C++ did not allow us to inherit private members of classes. Consider following example.

Example program


#include<iostream.h>

class A

{

private:

void show()

{

cout<<"Trustingeeks.com"<<endl;

}

};

class B:public A

{

};

main()

{

B obj;

obj.show();

}

Output

Friend Function

But what if some one want to access private members also?

Don’t worry C++ has ability to do that using friend function.

Friend Function

  • The function that is used to access the private and protected members of classes.
  • Friend function is just declared in class
  • Friend function is defined outside the class
  • In friend function the keyword “friend” must be used with function

Syntax of friend function

friend return_type functionName(arguments…);

friend function example


#include<iostream.h>

class B;  // declaration of class B

class A

{

private:

int a;   // private member of class A

public:

A()

{

a=10;

}

friend void sum(A,B);

};

class B

{

private:

int b;      // private member of class A

public:

B()

{

b=30;

}

friend void sum(A,B);

};

void sum(A obj1, B obj2)

{

cout<<"Sum = "<<obj1.a+obj2.b<<endl;

// both a and b are the private members of classes A and B respectively.

//But I can access it using friend function.

}

main()

{

A obj1;

B obj2;

sum(obj1, obj2);

}

Output

friend function in c++

function overloading in C++ example

C++ function overloading

C++ programming language permits you to define more than one definition of operators and function in one scope. One scope means that these operators or functions may be in one class etc. This technique is called overloading.

For example you have a class and in that class you can define functions with same name. this can only be possible by using function overloading.

To overload a function is called function overloading and to overload a operator is called operator overloading.

Example:

Let suppose you have a class A and you want to define two functions here. The function name should remain same. C++ does not allow you to do that simply without function overloading.

No function overloading


#include<iostream.h>

class A

{

public:

void sum()

{

cout<<"Trustingeeks.com"<<endl;

}

void sum()

{

cout<<"Trustingeeks.com"<<endl;

}

};

main()

{

A a;

a.sum();

}

Output

function overloading

 

As in above function overloading example compiler does not allow you to do that. But it is possible by using function overloading principles.

function overloading

Simple statement like

Void show (int a)

Above statement is called signature of the function. Functions whose signatures are not same can be overloaded. Declaring functions of different signature but same name is a same scope is called function overloading.

Important about function overloading!

You cannot overload a function by changing only its return type. Consider following example.


#include<iostream.h>

class A{

public:

int show()

{

return 10;

}

void show()

{

cout<<"RAFI AFRIDI"<<endl;

}

};

main()

{

A a;

a.show();

}

Output

Function overloading

 

Function overloading example


#include<iostream.h>

class A

{

public:

void sum(int a)

{

cout<<a+a<<endl;

}

void sum(char a)

{

cout<<a<<endl;

}

};

main()

{

A a;

a.sum(2);

//call fisrt sum function having int arguments

a.sum('S');

//call second sum function having char arguments

}

Ouput

function overloading

 

Some function overloading examples

sum(int a) and sum(int a, int b)

sum(int a) and sum(float b, int a)

int sum(int a, int b) and int sum (int a, float b, char c) etc.

Destructor in C++ programming

Destructor in C++

Destructor in C++ is also a function like constructor having following characteristics.

  1. It is a function
  2. Name same as class having tilde sign (~) before function name
  3. No return type
  4. Automatically execute when object is destroyed or out of scope.

Destructor is almost same as constructor but having tilde sign and automatically execute when object is destroyed or out of scope.

How object is created in C++?

When you simply declare object of class, which is object creation. Resources like memory are assigned to that object.

Example: Class_name obj;

An object name obj is created through above statement.

And in case of pointer we create pointer  through new operator.

Example: Class_name *ptr = new Class_name();

How object is destroyed in C++?

An object is destroyed by using delete operator with its pointer.

Example: delete ptr;

How destructor is called automatically?

When we delete the pointer using delete operator or when object finish its working and become out of scope.  Destructor executed automatically.

Example of destructor


#include<iostream.h>

class Trustingeeks

{

public:

Trustingeeks() // constructor

{

cout<<"Welcome..."<<endl;

}

void show()

{

cout<<"Trustingeeks site..."<<endl;

}

~Trustingeeks() // destructor

{

cout<<"Good bye..."<<endl;

}

};

main()

{

Trustingeeks obj;//object is created

//here constructor will execute

obj.show();//object working

//object is out of scope

//Or finsih working

//here destructor will execute

}

Output

destructor

 

 

Pointer delete example


#include<iostream.h>

class Trustingeeks

{

public:

void show()

{

cout<<"Trustingeeks site..."<<endl;

}

~Trustingeeks() // destructor

{

cout<<"Good bye..."<<endl;

}

};

main()

{

Trustingeeks *obj;

//pointer of class is created

obj->show();

}

Output

destructor in c++

 

In above program I create pointer of class Trustingeeks. Bu creating object constructor will execute not by creating pointer. But pointer like object does not destroy implicitly (by self). You have to delete pointer explicitly by using delete operator in C++.

In main function in above program just write statement

delete obj;

Pointer of that class will be destroyed. And upon destruction of pointer or object destructor execute automatically.

destructor

Why destructor is used?

Destructor is very useful for releasing resources occupied by that object or pointer or closing opened files. Resources may be like memory occupied.

 

Constructor c ++ examples

Constructor c ++ examples

Constructor c ++ and other languages is a function having following characteristics

  1. Name same as class name
  2. No return type
  3. Automatically called when object is declared

Note: void in c++ is used for none. But in case of constructor in c ++ you cannot used void in return type. If you do so program neither will nor compile.

Constructor c

Example of constructor c ++


#include<iostream.h>

class Rafi

{

private:

int age;

public:

Rafi()

{

age=22;

cout<<"my age is "<<age<<endl;

}

};

main()

{

Rafi obj;

}

Output

constructor c

 

If you observe above program I don’t call the function name Rafi() explicitly through object. It is automatically called, when I defined object of class. Here Rafi() function is basically constructor c ++.

If you write void with constructor c ++, the program will not run. Below I write void keyword with constructor c ++. Following error occurs.

constructor c

Constructor c ++ is basically used to initialized data of class. Following example will show you the fact.

Program without constructor c ++


#include<iostream.h>

class Rafi

{

private:

int count;

public:

void increment()

{

count++;

}

void show()

{

cout<<"Count = "<<count<<endl;

}

};

main()

{

Rafi obj;

obj.increment();

obj.show();

}

Output

constructor c

 

I only call increment() function once. But it shows very large value. It is garbage value. You are also not allowed to initialize values of data members in private, protected or public portions.

constructor in c

Program using constructor c ++

Now constructor c++ is used here to initialized data values to remove unwanted results. Modify above constructor c ++ program above.


#include<iostream.h>

class Rafi

{

private:

int count;

public:

Rafi()

{

count=0;

}

void increment()

{

count++;

}

void show()

{

cout<<"Count = "<<count<<endl;

}

};

main()

{

Rafi obj;

obj.increment();

obj.show();

}

Output

Constructor in c

 

Default constructor c ++

When there is no argument in constructor, such constructor is called default constructor c ++.

Parameterized constructor c ++

Constructor c ++ which has argument values. Like Rafi(int a), Rafi(int a, char ch) etc.

Example


#include<iostream.h>

class Table

{

private:

int no;

public:

Table(int num)

{

no = num;

}

void show()

{

for(int i=1; i<10; i++)

{

cout<<no<<" x "<<i<<" = "<<no*i<<endl;

}

}

};

main()

{

Table obj(5);  //this 5 will be send to constructor and store there in int no.

obj.show();

}

Output

constructor in c++

 

Initializer list

This is another method to initialize values in constructor c ++. Modify the constructor of above program simple like following. This will result same output.

constructor c

NOTE: If there are more than one arguments then simply put comma between arguments like this

Table(int num1, int num2) : no1(num1), no2(num2)

class in c plus plus understanding

class in c ++

class in c ++ is most important feature of object oriented programming.

Class is c ++ is user defined data type.

The collection of data and functions that manipulate data in class is called class in c ++.

Class in c ++ definition

Like every datatype in c++ classes must be defined before it is used.

Sysntax of class in c ++


class Name_of_class

{

Datatypes and member functions here…..

} ;

The keyword class must be used before Name to define class in c ++.

Then write the name of class. The name can be any word except keywords in c++. By convention the class name must start with capital letter i-e Math, Result etc.

Then the body of class occurs. And inside class body members of class in c ++ are defined.

At last the statement terminator (;) at end of class in c ++.

Defining object of class in c ++

Class in c ++ is only blueprint, object must be defined for it. Basically objects are created from class.

Syntax


Class_name     name_of_object;

How to accessed members of class

You cannot simply access data and function in OOP. You must first define object for that class and then through this object and an operator called dot operator you can access data and functions of class in c ++.

Syntax


Object_name.methodName();

Inside the class there are three regions used for various purposes.

  1. Private
  2. Protected
  3. Public

 


class Rafi

{

private:

protected:

public:

};

Private in class

If you want to hide your data from outside the class, you have to write that data in private portion of class in c ++.

This portion add encapsulation feature to Object Oriented Programming. Encapsulation is the data hiding.

class in c

Data and functions in private portion cannot be accessed from main as well from child classes. It can only be accessed in same class.

Same class can access private data and functions.

Child class cannot access private data and functions.

Main method cannot access private data and functions.

Example of private members


#include<iostream.h>

class OOP

{

private:

int a;

void show()

{

cout<<"Trustingeeks.com"<<endl;

}

};

main()

{

OOP obj;

obj.a; // error

obj.show(); //error

}

Output

class in c

Note: if you write nothing in class body in c++, by default is private. This make class in c ++ more secure than structures in c++.

Protected in class

If you want to make members (data and functions) to access by it child classes but not by other classes and main, you have to put it here.

Same class can access protected data and functions.

Child class can access protected data and functions.

Main method cannot access protected data and functions.

Example of protected members


#include<iostream.h>

class OOP

{

protected:

int a;

void show()

{

cout<<"Trustingeeks.com"<<endl;

}

};

class Child: public OOP

{

public:

void Display()

{

a = 10;

show();

}

};

main()

{

Child obj;

obj.Display();

}

Output

class in c

 

In above example of class in c ++ the int a, and show() both are protected and I call these members in display function which is in child class.

Public in class

If you want to make members (data and functions) to access by it child classes as well as by other classes and main, you have to put it here.

Same class can access public data and functions.

Child class can access public data and functions.

Main method can access public data and functions.

Example of public members


#include<iostream.h>

class OOP

{

public:

int a;

void show()

{

cout<<"Trustingeeks.com"<<endl;

}

};

main()

{

OOP obj;

cin>>obj.a;

cout<<obj.a<<endl;

obj.show();

}

Output

class in c

c polymorphism understanding

C++ polymorphism

C polymorphism is another most important characteristic of object oriented programming. In c polymorphism is achieved by using virtual functions, abstract classes and inheritance concept together. C polymorphism occurs only when there exist different classes in hierarchical manner related by inheritance.

C polymorphism consist of two words poly and morph. Poly means many and morph mean shapes.  Different processes are executed using same function call or statement is actually called c polymorphism.

To understood c polymorphism consider the following example.

c polymorphism example


#include<iostream.h>

class Shape

{

public:

void draw()

{

cout<<"Draw shape"<<endl;

}

};

class Circle : public Shape

{

public:

void draw()

{

cout<<"Draw circle"<<endl;

}

};

class Ellipse : public Shape

{

public:

void draw()

{

cout<<"Draw ellispe"<<endl;

}

};

main()

{

Shape *obj;

Circle c;

Ellipse e;

obj = &c;

obj->draw();   //c polymorphism

obj = &e;

obj->draw();   // c polymorphism

}

In above c polymorphism  example we actually want to call draw() derived classes. But it will show the base class draw() function although the base class pointer has derive class addresses.

Here the compiler looks for the type of pointer. The pointer is of shape type, so it will call draw() of shape.

Output

c polymorphism

 

Early binding or static binding

When we create pointer variable of base class “shape” in c polymorphism example above, function call to draw() is set fixed before program is executed. This property is called early binding or static binding. This is so called that function called is set fix at compile time.

But we can change it nature by using virtual keyword. Make the draw() function virtual.

c polymorphism

 

Now the output is change and appropriate. Why it is so?

By using virtual with function make draw() function virtual. Virtual keyword tells compiler that we don’t want early or static binding.  Now compiler will looks for the content of pointer. This is called late binding or dynamic binding.

c polymorphism

In above program we can defined the draw() of base class as well as we can create object of base class, although sometime there is no need of both. So we can avoid user by doing so intentionally or unintentionally.  C polymorphism provides us pure vitual function mechanism.

Pure virtual functions in c polymorphism

The virtual function that’s declare function in base class not to defined is called pure virtual function.

Syntax of pure virtual function

virtual draw() = 0;

There is no body of function. That tells compiler that this function will be defined by its child classes. Change the base class to following

c polymorphism

 

And second property of pure virtual function is that it will not allow us to create object of base class. It makes base class abstract. This class is called abstract base class.

c polymorphism

Abstract base class

In c polymorphism when we cannot create object of class, such class is called abstract base class. In above example class Shape is abstract base class.

Function overriding in C++

Function overriding

Function overriding in c++ is a concept of placing function over another function.

When a derived class and parent class contains functions having same name. Then question arise here is , The compiler will execute which of the function? This is called function overriding.

Example a class A having function show(). Another class is derived from it. It also contains a function show(). Now when we call show function through derive class object. Which function should compiler call? It may call it own function or may call parent class function because virtually it is present in derived class through inheritance.

When we call show() function the derive class function show() will execute, and we say that derive class function override parent class show() function. And this technique is called function overriding.

function overriding

Function overriding may be best explained with the help of following example.

Let you place history book on table. And above it you keep English book and math on top. So this may be analogous to function overriding. Where one book override another book same as one function override another function. If you see books from the top. You will see math book. Same is case in function overriding that function in child class is always execute.

Example


#include<iostream.h>

class Parent

{

public:

void show()

{

cout<<"Parent"<<endl;

}

};

class Child : public Parent

{

public:

/* this function show()

override show() in

parent class */

void show()

{

cout<<"Child"<<endl;

}

};

main()

{

Child c;

c.show();

}

Output

function overriding

 

More on function overriding

As in c++ programming is important in many situation. But if I want to execute the parent class show() first in child class show(). But compiler will not allow me. Change the show() function in above function overriding program as following.

function overriding

 

This problem can be solved through scope resolution operator(::).

Change the show() function in above function overriding program as following.

function overriding

multiple inheritance in C++

multiple inheritance in C++

Inheritance in C++ language is of two types

Single inheritance

Type of inheritance in which class is derived exactly from one another class.

You can understand single inheritance here , if you have no idea about it.

Multiple inheritance

Type of inheritance in which class is derived from more than one classes.

For example  a class Afridi is inherited from two classes Human and Student. Because that specific person has the properties of both Human and Student. Multiple inheritance allow us to reuse our code.

In following diagram three different class are written. The main problem here is that we have repeated code in each of the following classes.

multiple inheritance

By using Multiple inheritance concept we can avoid the repetition of code. Above classes can be written in following form after using multiple inheritance.

multiple inheritance

We have class name Ali having properties of Human class and Driver class. And class Rafi having properties  of Human and student class. Each of above class is derived from more than one class so it is multiple inheritance. We don’t have to write separate code in each of derived classes.

Multiple inheritance syntax

class child : type_of_inheritance Parent 1, parent 2, …… , parent N

Multiple inheritance example


#include<iostream.h>

class A

{

public:

void show1()

{

cout<<"A show()"<<endl;

}

};

class B

{

public:

void show2()

{

cout<<"B show()"<<endl;

}

};

class C : public A, public B

/* above statement is used to declare multiple

Inheriatance  */

{

};

main()

{

C obj;

obj.show1();

obj.show2();

}

 

In above program you have observed that show1() is present in class A and show2() is present in class B. But due to multiple inheritance it virtually present in class C because class C is inherited from class A and B. So it can be called through object of class C as shown below.

Output

multiple inheritance

 

Diamond problem in multiple inheritance

A special case in multiple inheritance when a class is derived from more than one class and each parent class contains function haiving same name. When you called that function by child class object. It will just confuse about function that what function should it call.


#include<iostream.h>

class A

{

public:

void show()

{

cout<<"A show()"<<endl;

}

};

class B

{

public:

void show()

{

cout<<"B show()"<<endl;

}

};

class C : public A, public B

{

};

main()

{

C obj;

obj.show();

}

Output

multiple inheritance

 

Solving Diamond problem in multiple inheritance

This type of problems can be easily solved by using scope resolution operator(::). Scope resoultion operator is used for referencing. For exampel if there is statement

Class_name :: function()

It means that function() belongs to that mention class.

Just change main() in above program like this

multiple inheritance

After changing statement obj.show() in main() to obj.A::show() following output will be shown.

multiple inheritance

What is meaning of obj.A::show()

Above statement simply tells compile that call the show() function of class A.

1

inheritance example in c++ language

inheritance in C++

One of the most important feature of object oriented programming is inheritance example in c++. Inheritance allows us to reuse the existing code written only once. Inheritance allow us to define class in another class. The inheritance example is same as real world inheritance, where properties of parent transfer to its children.

Inheritance can be best understood by the following example. For example a class FISH having two function swim() and breath(). Now if another class child_of_fish has also the same properties, then we don’t write it again. Inheritance example in c++ allow us to reuse the functions of parent class.

With inheritance example we must define two different classes having swim() and breath() function in both classes. We have to write function twice in our program. The program may become lengthy.

inheritance example

But if we use inheritance example discussed above. Then we have to write code once and use it again and again. With the help of inheritance example now the class will be like that.

inheritance example

The main advantage of inheritance eaxmple is that we don’t have to write repeated code. The inheritance in object oriented programming leads to facilty to reuse code.

Syntax of single inheritance in C++

Following syntax is of inheritance example.

  • class Child  :  type_of_inheritance Parent
  • Child is the name of child class
  • Parent is name of parent class.
  • Type_of_inheritance consist of three types
    • Private
    • Protected
    • Public

inheritance example in c++


#include<iostream.h>

class A

{

public:

void show()

{

cout<<"class A Function"<<endl;

}

};

class B : public A  //inherted B from A

{

// we dont write anything here

};

main()

{

B obj;   //object of class B

obj.show();

/*calling show()function of class A

with help of class B object. It will run

because automatically show() is

considerd in class B by using inheritance

example in C++ */

}

OUTPUT

inheritance example

 

NOTE:

  •   Parent class is also called base class and super class
  •   Child class is also called derived class and sub class
  •   In inheritance private member cannot be inherited.

Type of inheritance

Public inheritance

In public inheritance the protected member of parent class become protected member of child class

and public members of parent class become the public members of derive class.

Public inheritance example


#include<iostream.h>

class A

{

private:

int a, b;

public:

A()

{

a=10;

b=20;

}

void sum()

{

cout<<"Sum is "<<a+b<<endl;

}

};

class B : public A

{

 

};

main()

{

B object;

object.sum();

}

output

inheritance example in c

 

Protected inheritance

In protected inheritance the protected and public member of parent class become protected member of child class.

Protected c inheritance example


#include<iostream.h>

class A

{

private:

int a, b;

public:

A()

{

a=10;

b=20;

}

void sum()

{

cout<<"Sum is "<<a+b<<endl;

}

};

class B : protected A

{

 

};

main()

{

B object;

object.sum();

}

Output

Above is inheritance example of protected type. The public member sum() becomes the protected member of child class. So it cannot be accessed in main(). But can be accessed in its child class.

inheritance example in c++

 

Private inheritance

In private inheritance the protected and public member of parent class become private member of child class.

Private inheritance example


#include<iostream.h>

class A

{

private:

int a, b;

public:

A()

{

a=10;

b=20;

}

void sum()

{

cout<<"Sum is "<<a+b<<endl;

}

};

class B : private A

{

};

main()

{

B object;

object.sum();

}

Output

Above is inheritance example of private type. The public member sum() becomes the private member of child class. So it cannot be accessed in main() as well as in its child class.

inheritance example in c++

 

For better understanding of inheritance example


class A

{

private:

// code 1;

protected:

//code 2;

public:

//code 3;

};

class B : public A

{

//code 1 is not accesible here.

//code 2 is protected member here

//code 3 is public member here

};

class B : protected A

{

//code 1 is not accesible here.

//code 2 is protected member here

//code 3 is protected member here

};

class B : private A

{

//code 1 is not accesible here.

//code 2 is private member here

//code 3 is private member here

};

Android Mobiles Available within Most Reasonable Prices

Android Mobiles Available within Most Reasonable Prices:Android, developed by Google, is the most popular operating system for smartphones. In just a few years, it has managed to capture much of the market and is only in competition with Apple’s iOS. Android is used on smartphones from almost all major smartphone companies, such as Samsung, HTC, Huawei and QMobile. It remains popular among smartphone users mainly because of its customizability and versatility, along with the thousands of applications that Google offers through its Playstore. While shopping online for smartphones, don’t forget to browse Shophive and kaymu.pk for collection of smartphones. Below are some affordable Android devices available in Pakistan:

QMobile Noir A75

android phones at resonable price

QMobile has made a name for itself in Pakistan, thanks to the variety it offers in extremely affordable prices. Its phones feature top-quality specs at a price that other companies would charge a double of. The QMobile Noir A75 is one such phone. It has a 4.5inch screen and runs on Android Jelly Bean. Powered by a 1GHz dual core processor and working on a 1500mAh battery, it is a powerful smartphone that takes care of all your necessary communication needs. It also has an FM radio and a 3 MP rear camera, along with a secondary VGA camera.

Huawei Ascend Y330

android mobile phones at resonable price

Huawei is another company that offers great value for money. A Taiwanese technological giant, is had managed to attract quite a considerable percentage of the local population due to its affordability. The Huawei Ascend Y330 is one of the most sought after phones from Huawei. It runs on Android Jelly Bean and has a built in internal memory of 4GB. Featuring a 3.15 MP camera with geo-tagging option, along with Bluetooth, GPRS, USB and WLAN, this phone has got it all.

Voice Xtreme V14

android phones at best price

Voice is a Pakistani brand that has acquired some fame in recent years. It offers incredibly affordable phones that are packed with features. The Voice Xtreme V14 is one such phone that offers amazing specs. It is equipped with 1.2 GHz processor and a 4 GB built in internal memory. Also featuring Bluetooth, USB, WLAN, GPRS, EDGE and FM Radio, along with a 3.2 MP camera with flash light, this phone has become one of the favorites among users looking for feature-rich affordable smartphones.

QMobile Noir X11

android mobile phones avialiable

QMobile has come up with so many innovative models that it is impossible that it does not make it to the list of affordable smartphones at least twice. The QMobile Noir X11 is an impressive smartphone that offers the latest version of Android that is Kit Kat. Powered by a 1 GHz dual-core processor, equipped with a 3.2 MP camera, along with an array of exciting features, this phone has everything you ask for.

Samsung Galaxy Star

android mobiles avialable

Samsung is expected to be featured wherever one talks about good quality phones. Although Samsung has created a niche for itself in the high end smartphone market, Samsung has also caused quite a stir for its affordable phones. The Samsung Galaxy Star is a fast-performing smartphone running on Android Jelly Bean, powered by a 1 GHz processor. A 2MP camera, Bluetooth and USB capability, dual-sim option, and many more features make it an appealing investment.