Archive

Category Archives for "c++ programing"
1

creating Date class in c++

Creating  date class in which  member data may consist of three integers: like day, month, and year.

three member functions:
getdate( ) which allows the user to input  a date,displaydate( )/showdate() function which
displays the date the last changeformat( ) function which change the date in
mm/dd/yyyy format. */


#include<iostream.h>
class Date{
private:
int day,month,year;
public:
Date():day(0),month(0),year(0){}
void getdate(){
cout<<"Enter day:"<<endl;
cin>>day;
cout<<"Enter month:"<<endl;
cin>>month;
cout<<"Enter year:"<<endl;
cin>>year;
}
void showdate(){
cout<<day<<"-"<<month<<"-"<<year<<endl;}
void changeformat(int a, int b, int c){ day=a;
month=b;
year=c;
cout<<month<<"/"<<day<<"/"<<year<<endl;

} };

main()
{
Date b;
b.getdate();
b.showdate();
b.changeformat(12,3,2011); }

2

interview questions in c ++

Interview questions in C ++

1) Is C++ is case sensitive?

YES, C++ is case sensitive. You cannot write MAIN instead of main.


2) Write simple C++ program.


#include<iostream.h>

using namespace std;

//main() is portion where program executions begins.

main()

{

cout<<"RAFI ULLAH AFRIDI"<<endl;

// cout is used to print something on screen

}


3)


4) What is compiler?

Compiler is a translator which translate our high level language in to low level language (also called machine language) and low level language to high level language.

Because machine don’t understand our high level language such as

int a;

cin>>a;

cout<<a<<endl;

compiler will convert this into machine language like

0010010101011100

something like that. And then process it and result is converted again into high level language.


5) What are comments in C++ program and why it is used?

Comments are that lines in C++ program which we don’t want to compile but we want to write it down in C++ program. Those lines which are commented in C++ program will be simply ignored by compiler.

And it is used for users to understand each and every step in C++ program code.


6) how many types of comments are there?

There are two types

Single line comment:- “//” symbol is used if we want to comment a single line.

Multiple line comments:- if we want to comment whole paragraph. It is recommended to use this.

/* Program comments are explanatory statements that you can include in the C++ code that you write and helps anyone reading it’s source code. All programming languages allow for some form of comments.  */

Lines or statement between /* and */ will be simply ignored by compiler.


7) what is function of endl?

endl is used for new line. “\n” is also used for new line.


8) What is variable?

variable is named part of memory where we store our data.

int a;

above statement means the part of memory named “a” where we can store integer value.


8) What kind of name we should use for variables?

Every words can be used for variable name except keywords.

the variable name should start with lower case alphabet. Like

int value;                            // valid name

int age of boy;                   // invalid name

int gpa_of_student;        // valid name


9) what are keywords?

Keywords are specail words used by C++ language. We cannot use it for naming purposes.

for example

int float;              // invalid name because its keyword.

int include;        // invalid name because its keyword.


10) What are keywords used in C++?

Following keywords(also called reserve words) are use in C++.

int, float, main, iostream, iomanip, include, bool, double, long, unsigned etc.


11) Types of data

Following are some of the datatypes

int:- used for integer values

char:- used for character values

float:-  a single precision floating point value

double:- double precision floating point value

void:-  this represents the absence of datatype

bool:-  used for true and false values only


12) What are kinds of variables?

There are two types

Local variable:-  variable defined by some specific function. And only accessible in that function.

Global variables:- variables defined above main function and accessible by whole program.


#include<iostream.h>

using namespace std;

int age;      // global variable

main()

{

int age;      // local variable

cout<<"RAFI ULLAH AFRIDI"<<endl;

}


13) What is main difference between local and global variables?

  • Local variables are not initialized automatically by system.
  • Default values are garbage values.
  • Visible only in function which defined it.

=====+=======+=======+=======+=======+=======+========+=========+========+

  • Global variables initialized automatically by system.
  • Defaults values for int, float, double is O and for pointer is NULL and for char is ‘\o’.
  • visible in whole program.

14) In how many ways we can define constant in C++?

There are two ways to define constant in C++

(1) #define PI 3         // this means that PI has value 3

(2) const int PI = 3;   // this means that PI has value 3


15) What operators are used in C++?

Arithmetic Operators (+, -, *, /, %)

Relational Operators (==, <=, >=, <, >!=)

Logical Operators (!, &&, ||)

Bitwise Operators (|, &, ^)

Assignment Operators (=, +=, -=, *=, /=)

Misc Operators (?:, *, sizeof)


16) What is meant by infinite for loop?

infinite for loop means the loop that will run forever. i-e not ending


#include<iostream.h>

using namespace std;

main()

{

for(; ; 😉

{

cout<<"This is infinite loop, it will never stop"<<endl;

}

}


 

 

1

Template in C ++ examples

Template in C++

templates are the basis of generic programming. Which means write code independent of data types.

Template in C ++ is actually a formula or blueprint or map for creating generic programs.

Template in C ++ can be used with functions as well as classes.

 Function template in C ++

A generic function which is coded and independent of specific datatype is called template function.

Real world example

Template in C ++ is like a structure or map of a single room in building and then all rooms can be constructed using same structure or map. Analogous to that example a function template in  C++ can be used for each of that datatype in C++.

c template

We must write separate functions for processing different datatypes.

Example


#include<iostream.h>

void sum(int a, int b)

{

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

}

main()

{

sum(2,3);

}

Output

template in C

 

Now pass two float values as argument to function. See result

template in C

Now pass two float values as argument to function. See result

template in C

The above all results are not actually we expecting. So we must write separate functions for these. But template in C ++ allow us to write function only once and used as generic function for all the data types.

Syntax of function template


template <class T>

T function_name(T varible1, T variable2,...)

T in above syntax of template in C ++ is actually datatype which may be anyone of datatypes in C++. T may integer, char or float etc.

Example of function template


#include<iostream.h>

template <class T>

void sum(T a, T b)

{

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

}

main()

{

sum(2,3);

sum('R','S');

sum(3.4,4.5);

}

Output

template in c

 

Class template in C ++

Same as function template in C ++, class template in C ++ is used in generic programming and class template in C ++ is used as blueprint.

Syntax of class template in C++


template <class T>

class class_name{};

Example of class template in C ++


#include<iostream.h>

template <class T>

class Student

{

private:

T var[10];

public:

void show(T vari[10])

{

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

{ cout<<vari[i]<<" , "; }

cout<<endl;

}

 

};

main()

{

int i[10]={1,2,3,4,5,6,7,8,9,10};

Student<int> obj;

obj.show(i);

 

char c[10]={'R','A','F','I','U','L','L','A','H','!'};

Student<char> obj1;

obj1.show(c);

 

float f[10]={1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9,10.10};

Student<float> obj2;

obj2.show(f);

}

Output

template in C

In above template in C ++ example it has been cleared that we have a class used to process different datatype. But at the time of creating objects of that class objects must be declared that it is of which type. To do that we used the following syntax.


Student<int> obj;


This shows that it is arrays of integers.


Student<char> obj1;


This shows that it is arrays of characters.


Student<float> obj2;


This shows that it is arrays of float.


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

1 2 3