Just thought of having a simple example which has everything you need to know about the basics of C++. It has Inheritance, polymorphism, operator overloading, templates using friend as well as non-friend functions.

Code: Cpp

#include <iostream>

using namespace std;

template <typename T>

class Base

{

protected:

T strQuery;

public:

Base(T q = NULL): strQuery(q){}

Base(Base<T> &b): strQuery(b.strQuery){}

~Base(){}

T getQuery(void){return strQuery;}

void setQuery(T q){strQuery = q;}

};

template <typename T>

class Derived : public Base<T>

{

public:

//Default Functions also provided

Derived(const T q = NULL): Base<T>(q){}

Derived(const Derived &d): Base<T>(d.strQuery){}

~Derived(){}

Derived<T> operator=(const Derived<T> d)

{

if(this != &d)

this->strQuery=d.strQuery;

return *this;

}

//Input Output Functions

friend ostream& operator <<(ostream&,const Derived<T>&);

friend istream& operator >>(istream&,Derived<T>&);

//op + Functionality

Derived<T> operator + (const Derived<T>) const;

Derived<T> operator + (const T) const;

friend Derived<T> operator + (const T,const Derived<T>);

Derived<T>& operator ++ ();

Derived<T>& operator ++ (int);

Derived<T>& operator += (const Derived<T>);

};

template<typename T>

ostream& operator <<(ostream& out,const Derived<T>& d)

{

out<<d.strQuery;

return out;

}

template<typename T>

istream& operator >>(istream& in,Derived<T>& d)

{

in>>d.strQuery;

return in;

}

template<typename T>

Derived<T> Derived<T>::operator + (const Derived<T> d) const

{

Derived<T> temp;

temp.strQuery = this->strQuery + d.strQuery;

return temp;

}

template<typename T>

Derived<T> Derived<T>::operator + (const T t) const

{

Derived<T> temp;

temp.strQuery = this->strQuery + t;

return temp;

}

template<typename T>

Derived<T> operator + (const T t,const Derived<T> d)

{

Derived<T> temp;

temp.strQuery = d.strQuery + t;

return temp;

}

template<typename T>

Derived<T>& Derived<T>::operator ++ ()

{

++(this->strQuery);

return *this;

}

template<typename T>

Derived<T>& Derived<T>::operator ++ (int)

{

this->strQuery++;

return *this;

}

template<typename T>

Derived<T>& Derived<T>::operator += (const Derived<T> d)

{

this->strQuery += d.strQuery;

return *this;

}

int main(int argc,char *argv[])

{

Derived<double> d1,d2(10);

Derived<double> d3(d1);

cout<<"Enter Number\n";

cin>>d1;

cout<<d1;

cout<<endl;

d2=d1;

d3 = d1 + 1;

d3 = d2++;

d3=++d2;

d3 = d2 = d1 = 1.2L;

d3 += d2;

cout<<d3<<"\t"<<d2<<"\t"<<d1<<"\n";

return 0;

}