Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

C

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 67

C++ Tutorials

1.1 1.2 C++ Basic's Tutorial Learn C++ in Easy Way

C++ Examples
2.1 C++ Basic Examples

C++ Interview Questions with Answers


3.1 3.2 3.3 3.4 3.5 3.6 C++ Subjective Questions with Answers C++ Interview Questions with Answers C++ Objective Questions And Answers C++ Interview Questions And Answers (Subjective) C++ Objective Questions FAQS

Introduction Of C++:
C++ is a Computer Programming Language .it is an "object oriented" programming language created by Bjarne Stroustrup and released in 1985. It implements "data abstraction" using a concept called "classes", along with other features to allow objectoriented programming. Parts of the C++ program are easily reusable and extensible; existing code is easily modifiable without actually having to change the code. C++ adds a concept called "operator overloading" not seen in the earlier OOP languages and it makes the creation of libraries much cleaner. C++ maintains aspects of the C programming language, yet has features which simplify memory management. Additionally, some of the features of C++ allow low-level access to memory but also contain high level features. C++ could be considered a superset of C. C programs will run in C++ compilers. C uses structured programming concepts and techniques while C++ uses object oriented programming and classes which focus on data. Binding Architecture of C++:

History of C++: C++ was written by Bjarne Stroustrup at Bell Labs during 1983-1985. C++ is an extension of C. Prior to 1983, Bjarne Stroustrup added features to C and formed what he called "C with Classes". He had combined the Simula's use of classes and object-oriented features with the power and efficiency of C. The term C++ was first used in 1983. Prior to C++, C was a programming language developed at Bell Labs circa 1969-1973. The UNIX operating system was also being developed at Bell Labs at the same time. C was originally developed for and implemented on the UNIX operating system, on a PDP-11 computer by Dennis Ritchie. He extended the B language by adding types in 1971. He called this NB for New B. Ritchie credited some of his inspiration from theAlgol68 language. Ritchie restructured the language and rewrote the compiler and gave his new language the name "C" in 1972. 90% of UNIX was then written in C. The committee that wrote the 1989 ANSI Standard for C had started work on the C Standard project in 1983 after having been established by ANSI in that year. There were quite a number of versions of C at that time and a new Standard was necessary. Feature of C++: The main features of the C++ are 1. 2. 3. 4. 5. 6. Classes Inheritance Data abstraction and encapsulation Polymorphism Dynamic Binding Message Passing

Advantage of C++:

1. C++ is a hybrid language-it is possible to program in either a C-like style, an objectoriented style, or both. 2. C++ programs consist of pieces called classes and functions. You can program each piece you may need to form a C++ program. The advantage of creating your own functions and classes is that you will know exactly how they work. You will be able to examine the C++ code. Disadvantage of C++: 1. 2. 3. 4. 5. 6. Scope is also limited Platform dependent Does not give excellent graphics as compare to java Not case sensitive Less features as compared to Java& C#. Not applicable in web environment

C++ Basics Tutorial


1. Introduction and history of C++ 2. Advantage and Disadvantage of C++ and Scope 3. The Parts of a C++ Program 4. Variables 5. Constants 6. Expressions 7. Statements 8. Basic Classes 9. Inheritance 10.Types of Inheritance (Single, Multiple ) 11.Types of Inheritance (Hierarchal, Multilevel, Hybrid) 12.Polymorphism

Variables of C++
A variable is the temporary storage space in memory stored by its value. variable can be represented by their name . The variable name can be any think like set of one or more letters, digits or underscore. Rules for defining variable name:

A variable name can have set of letters or digits or underscore . A variable name can't have White space, punctuation symbols or other characters . A variable name must begin with a letter. Keywords or any reserved words cannot be of variable names. Variable names written in capital letters and small letters are different variable because C++ is a case-sensitive language

Declaration of variables: before declaring a variable first should think about data type of variable and also the name of the variable .Name of the variable should have some meaning .Data type in C++ is as: data_type variable_name; short int :used to represent short integer. int: used to represent integer. long int: used to represent long integer. float: used to represent floating point number. double: used to represent double precision floating point number. long double: used to represent double precision floating point number. char: used to represent a single character. bool: used to represent two values: True or False.

Type unsigned short int short int unsigned long int long int int unsigned int char bool float double
#include <iostream> using namespace Beg;

Size 2 bytes 2 bytes 4 bytes 4 bytes 4 bytes 4 bytes 1 byte 1 byte 4 bytes 8 bytes

Values 0 to 65,535 32,768 to 32,767 0 to 4,294,967,295 2,147,483,648 to 2,147,483,647 2,147,483,648 to 2,147,483,647 0 to 4,294,967,295 character values true or false 1.2e38 to 3.4e38 2.2e308 to 1.8e308
//include header file //main function with int return type // declaration // declaration //object of in stream //object of output stream //object of output stream

int main() { int a; int sum=0; cin>> a; cout << "value of a is.\n",a; sum= sum+a; cout << "sum is.\n",sum;

return 0; }

//return function

value of a.10 sum is.10 Reference Variable: A reference variable provide an alias (alternative name) for a previously defined variable name. data_type & reference_name = variable_name; Constant Of C++
constant are like variable but the difference between constant and variable is that constant value fixed it can't change in whole program but variable value can change during program. Enumeration Constant An enumeration data type, data type represents a set of identifiers. Each identifier in this set is an enumeration constant. The value of the enumeration constant is determined as: In enumeration constant assigned to the explicit value for set of identifier. If no explicit value is assigned, the leftmost constant in the set of receives the value zero (0). If in the set of integer identifiers with no explicitly assigned values that is one greater than the value represented by the previous identifier.

When declare const its must have initializes means in left hand contain the name of constant and in right hand side have the value of that constant except those referencing externally defined constants . If constant is an integer then const object can appear in a constant expression and it is initialized to a constant. The following example:

const int number = 200; int ary[number]; /* allowed in C++*/. If a global const object have no any explicit storage class then it consider as static const by default. const int number = 12; static const int number1 = 120; extern const int number2 = 121;

Because its linkage is assumed to be internal, a const object can be more easily defined in header files in C++ than in C.

Expressions

Expression An expression is a combination of operators, constants and variables. It also include function call which return values. An expression may include one or more operators. The operator in C++ are: Arithmetic operators Operator name Basic assignment Addition Subtraction Unary minus Unary plus Multiplication Division Modulo (remainder) Increment Decrement Syntax a=b a+b a-b -a +a a*b a/b a%b ++ -++a --a a++ a-Prefix Suffix

Comparison operators/Relational operators Operator name Equal to Not equal to Greater than Less than Greater than or equal to Less than or equal to Logical operators Operator name Logical negation (NOT) Logical AND Logical OR !a a && b a || b Syntax a ==b a !=b a>b a<b a >=b a <=b Syntax

Bitwise operators
Operator name Bitwise NOT ~a Syntax

Bitwise AND Bitwise OR Bitwise XOR Bitwise left shift Bitwise right shift

a&b a|b a^b a <<b a >>b

Compound-assignment operators
Operator name Addition assignment Subtraction assignment Multiplication assignment Division assignment Modulo assignment Bitwise AND assignment Bitwise OR assignment Bitwise XOR assignment Bitwise left shift assignment Bitwise right shift assignment a += b a -= b a *= b a /= b a %= b a &= b a |= b a ^= b a <<=b a >>=b Syntax

Type of Expression: Constant Expression

Example: 20 29+48%2 Integer Example: m+n-2 29+int(222.3) Float Expression Example: m+n 294+float(2224) Pointer Expression Example:

Expression

&m ptr ptr+1

Relational Expression

Example: a+b==c+d x<=y m+n>100

Logical Expression

Example: a>b && x==1098 x==200 ||y==20

Bitwise Expression

Example: a>>1098 x<<200

Statement
if Statement: In if statement condition evaluated if condition is true then statement with in if block will be executed otherwise control go to else block will executed. Simple if statement if_else statement

Simple if statement: if (expression is true) { statement1; } statement2; statement3; if_else statement: if (expression is true) { statement1;

} else { statement2; } statement3; if (x == 203035) cout << "x is 203035"; else cout << "x is not 203035"; Switch Statement:

// if statement //else statement

This is a multi branching Statement which is based on condition. Control is transfer to one of the many statements. switch (expression) { case 1: { statement 1: . . . statement n; } case 2: { statement 1: . . . statement n; } . . . . default: { statement 1: . . . statement n; } } statement;

do while statement: This is statement where first loop executed then condition evaluated.

do { statement 1; } while (condition is true); statement n ;

while statement:
#include <iostream> using namespace std; int main () { int number; cout << "Enter the initial > "; cin >> n; while (n<10) { cout << n << ", "; ++n; } cout << "OUT!\n"; return 0; Enter the initial>1 1,2,3,4,5,6,7,8,9,10,OUT!

for Statement:
for(initial value; test condition; increment/decrement) { statement 1; . . . statement n; }

Basic Classes
Class is use for bind data and its operated function together. For external use its necessary to hidden the data and function. Or Class is the container of object. Class Specification have two part:: Class Declaration Class Function definitions

Class Declaration:

class class_name { private: variable declarations; function declarations; public: variable declarations; function declarations; }; The keyword class specified that what follow in an abstract data of type class_name. private and public are access modifier. where private is visible with is the class where public data member is can be access with in the class and also outside the class.

class class_name { private: int num1; float num2; public: void getdata(int num1,float num2); void putdata(void); }; Create Objects Object is real time entity. Object have some attribute and also some feature. Object can created with class name asclass_name object_name; And also created as:

class class_name { private: int num1; float num2; public: void getdata(int num1,float num2); void putdata(void); } c1,c2,c3; Class Function Definition: Member function can be defined in two ways:

//object created.

Out Site the class definition Inside the class definition

Outsite the class definition return_type class_name:: function_name(argument declare) { function body; } Inside the class definition

class class_name { private: int num1; float num2; public: { } { } } c1,c2,c3; void getdata(int num1,float num2) cin>>num1; cin>>num2; void putdata(void); cout<<num1; cout<<num2; //object created. // inside class declaration // inside class declaration

Inheritance In C++ Inheritance is used for reusability of codes. One of the important feature of OOP is reusability. It's done through creating new classes, and reuse the feature and attribute of existing old one . The mechanism where feature and attribute of an old class is deriving to a new class is called inheritance. The old class is referred to as the base class and the new one is called the derived class or subclass. The derived class or subclass can acquire the some or all property of base class. Derived class have its own feature and also the feature of its super or base class. Defining The Derived Class: Derived class are those classes who inherit the property of base class. In any program can have many base class and also have many derived classes .
class derived_class_name : access_modifier base_class_name { ....... //members 0of derived class

........ ........ };

//members 0of derived class //members 0of derived class

class base { //member of base class }; class derive1: private base //private derivation { //member of derived1 }; class derive2: public base //public derivation { //member of derived2 }; class derive3: base //private derivation by default { //member of derived3 }; Private Inheritance: when derived class is private inherited the base class then public member of the base class is become private member of the derived class. When a derived class inherit the base class then member function of derived class can only access the public member of base class. when base class is privately inherited then no member of the base class is accessible to the object of derived class. Public Inheritance: when derived class is public inherited the base class then public member of the base class is become public member of the derived class. When a derived class inherit the base class then member function of derived class can only access the public member of base class. when base class is publicly inherited then public member of the base class is accessible to the object of derived class. But in both cases private member of the base class can't inherited therefore private members of a base class will never become the member of its derived class. #include<iostream> class Rectangle { private: float length ; // private member and data can't inherited public: float width ; // public member and data are inheritable void dimention() // public member and data are inheritable { cout << "\n Enter the length of the rectangle : "; cin >> length ; cout << "\n Enter the width of the rectangle : ";

cin >> width ; } float length1() { return length ; } };

// The public member and data are inheritable // End of the class definition

class RectangleArea : public Rectangle { private: float area ; public: void Rec_area(void) { area = length1() * width ; //length can't access directly because its a private member of base class } void Display(void) { cout << "\n Length = " << length1() ; //length can't access directly because its a private member of baseclass cout << "\n width = " << width ; cout << "\n Area = " << area ; } }; // End of the derived class definition void main(void) { RectangleArea area1 ; area1.length1(); // The public member and data so its access through the object of derived class. area1.Rec_area( ); area1.Display( ); }

Types of Inheritance( Single, Multiple)


Single Inheritance Multiple Inheritance Hierarchal Inheritance Multilevel Inheritance Hybrid Inheritance

Single Inheritance: One derived class inherit the public members of base class. In single inheritance there is single base class and also single derived class .Derived class can access only public member of base class and can access the public member through derived class objects.

#include<iostream> class Cals // Base class { private: float number1 ; // private member and data can't inherited public: float number2; // The public member and data are inheritable void getdata() // The public member and data are inheritable { cout << "\n Enter the number1 of the Cals : "; cin >> number1 ; cout << "\n Enter the number2of the Cals : "; cin >> number2; } float first_number() // The public member and data are inheritable { return number1 ; } }; // End of the class definition class Calculate : public Cals //Derived class { private: float result1 ,result2,result3,result4; public: void sum(void) { result1 = first_number() + number2;//number1 can't access directly because its a private member of base class } void substract(void) { result2 = first_number() - number2;//number1 can't access directly because its a private member of base class } void multi(void) { result3 = first_number() * number2;//number1 can't access directly because its a private member of base class } void div(void)

{ result4 = first_number() / number2;//number1 can't access directly because its a private member of base class } void Display(void) { cout << "\n number1 = " << first_number() ; //number1 can't access directly because its a private member of base class cout << "\n number2= " << number2; cout << "\n sum is = " << result<< "\n substraction is = " <<result2<< "\n multiplication is = "<<result3<< "\n division is = "<<result4; } }; // End of the derived class definition void main(void) { Calculate cal ; cal.first_number(): // The public member and data so its access through the object of derived class. cal.sum( ); cal.substract( ); cal.multi( ); cal.div( ); cal.Display( ); }

Multiple Inheritance: In multiple inheritance there are two are more base class is there. When a derived class inherit the member function of two or more classes .Multiple inheritance allow to combine the feature of more then two classes with in a single derived class . Types of Inheritance( Hierarchal, Multilevel, Hybrid)
Hierarchal Inheritance: In this inheritance ,is use hierarchal design. Here a base class is derived to other two or more derived class and then derived class is become base class for next level derived class. This include multilevel inheritance .

Structure of Hierarchal Inheritance: # include<iostream.h> class base { .... ..... // class body ..... };

class derived1:public base { .... ..... // class body ..... }; class derived2:public base { .... ..... // class body ..... }; class derived3:public base { .... ..... // class body ..... }; class derived2_a:public derived2 { .... ..... // class body ..... }; class derived2_b:public derived2 { .... ..... // class body ..... }; class derived2_c:public derived2 { .... ..... // class body ..... }; Structure of Hierarchal Inheritance: #include<iostream> const int num = 20 ; class student // Base class { private: char F_name[num] , L_name[num] ; int age, int roll_no ; public: void Enter_data(void) { cout << "\n\t Enter the first name: " ; cin >> F_name ; cout << "\t Enter the second name: "; cin >> L_name ; cout << "\t Enter the age: " ; cin >> age ; cout << "\t Enter the roll_no: " ; cin >> roll_no ; } void Display_data(void)

{ cout << "\n First Name = " << F_name ; cout << "\n Last Name = " << L_name ; cout << "\n Age = " << age ; cout << "\n Roll Number = " << roll_no ; } }; class arts : public student //derived class of same base class { private: char subject_name1[num] ; char subject_name2[num] ; char subject_name3[num] ; public: void Enter_data(void) { cout << "\t Enter the subject1 : "; cin >> subject_name1 ; cout << "\t Enter the subject2 "; cin >> subject_name2 ; cout << "\t Enter the subject3 "; cin >> subject_name3 ; } void Display_data(void) { cout << "\n Subject1 = " << subject_name1 ; cout << "\n Subject2 = " << subject_name2 ; cout << "\n Subject3 = " << subject_name3 ; } }; class arts : public student //derived class of same base class { private: char s_subject_name1[num] ; char s_subject_name2[num] ; char s_subject_name3[num] ; public: void Enter_data(void) { cout << "\t Enter the subject1 : "; cin >> s_subject_name1 ; cout << "\t Enter the subject2 "; cin >> s_subject_name2 ; cout << "\t Enter the subject3 "; cin >> s_subject_name3 ; } void Display_data(void) { cout << "\n Subject1 = " << s_subject_name1 ; cout << "\n Subject2 = " << s_subject_name2 ; cout << "\n Subject3 = " << s_subject_name3 ; } }; class commerce : public student //derived class of same base class { private: char c_subject_name[num],c_subject_name2[num],c_subject_name3[num] ;

public: void Enter_data(void) { cout << "\t Enter the subject1: "; cin >> c_subject_name; cout << "\t Enter the subject2 : "; cin >>c_subject_name2 ; cout << "\t Enter the subject3 : "; cin >>c_subject_name3 ; } void Display_data(void) { cout << "\n Subject1 = " << c_subject_name ; cout << "\n Subject2 = " <<c_subject_name2 ; cout << "\n Subject3 = " <<c_subject_name3 ; } }; void main(void) { arts a ; cout << "\n details of the arts student\n" ; a.Enter_data( ); cout << "\n details of the arts student\n" ; a.Display_data( ); science s ; cout << "\n details of the science student\n" ; s.Enter_data( ); cout << "\n details of the science student\n" ; s.Display_data( ); commerce c ; cout << "\n details of the commerce student\n" ; c.Enter_data( ); cout << "\n details of the commerce student\n"; c.Display_data( ); } Multilevel Inheritance: In multilevel inheritance where a derived class inherit the property on one base class and that derived class is become the base class for another derived class. For example A is a base class and B inherit the property of A here B is a derive class and another class C is inherit the property of class B now class B become the base class for class C and class C is derived class For class B. class A indirectly base Class of Class C and class C indirect derived class for class A.

Structure of Hierarchal Inheritance: # include<iostream.h> class base { .... ..... ..... };

// class body

class derived1:public base // derived from base class { .... ..... // class body ..... }; class derived2:public derived1 // derived from derived class { .... ..... // class body ..... }; Structure of Multilevel Inheritance: # include<iostream.h> class student { protected: int roll_num; public: void enter_number(int a) { roll_num=a; } void display_number(void) { cout<<"Enter roll number is"<<roll_num<<"\n"; } }; class test : public student //First level derivation { protected: float subject1: float subject2; public: void enter_marks(float x, float y) { subject1=x; subject2=y; } void display_marks(void) { cout<<"marks of subject1"<<subject1<<"\n"; cout<<"marks of subject2"<<subject2<<"\n"; } }; class result : public test //Second level derivation { float total; public: void display(void) { total=subject1+subject2;

display_number(); display_marks(); cout<<"total ="<<total<<"\n"; }; } int main() { result re; re.enter_number(100); re.enter_marks(76.5,77.5); re.display(); return 0; } }; Hybrid Inheritance: In hybrid Inheritance , this is combination of two or more type of inheritance . but in hybrid inheritance the error will occur is known as ambiguity . Where same function name can have more then one class then compiler confused to identify called function. Structure of Hybrid Inheritance: # include<iostream.h> class student { protected: int roll_num; public: void enter_number(int a) { roll_num=a; } void display_number(void) { cout<<"Enter roll number is"<<roll_num<<"\n"; } }; class test : public student //First level derivation { protected: float subject1: float subject2; public: void enter_marks(float x, float y) { subject1=x; subject2=y; } void display_marks(void) { cout<<"marks of subject1"<<subject1<<"\n";

cout<<"marks of subject2"<<subject2<<"\n"; }; class sport { protected: float score; public: void enter_ score(int i) { score=i; } void display_ score(void) { cout<<"Enter score is"<< score<<"\n"; } class result : public test { float total; public: void display(void) { total=subject1+subject2+ score; display_number(); display_marks(); display_ score(); cout<<"total ="<<total<<"\n"; }; int main() { result re; re.enter_number(1234); re.enter_marks(27.5,33.0); re.enter_score(6.0); re.display(); return 0; } }

}; OUTPUT:

Enter roll number is 1234 marks of subject1 27.5 marks of subject2 33 Enter score is 6 total=66.5

Polymorphism
Polymorphism means one thing in many form. In polymorphism operators and functions can use in many forms. Single operator behave different for different data type. Such as addition operator use to add integer and concatenate for string. Polymorphism is the

concept where one same function or operator send to many different object how perform different operation and result is also different. There are two types of polymorphism: Static Polymorphism Dynamic Polymorphism

Static polymorphism refers to an many similar entity existing in continuous but have slight difference. Static polymorphism many functions have some differences as number, type, and sequence of arguments. When function declaration the various types of parameters are specified ,and therefore the function can be bound to calls at compile time. This phenomena is called early binding. The term early binding the calls of parameter , return type are already bound to that functions when program is executed. At the time of compilation this function bind that's why its known as early binding. Function Overloading: In function overloading provide the facility that with in the same class more then one function can have same name but the number , type and appearance of the argument or parameter must be changed. How to declare Function in function overloading:

void fun(); // Overloaded void fun(int i,float j); // Overloaded void fun(float j,inti); // Overloaded void fun(int i, int j); // Overloaded void fun(int j, int i); // Overloaded int fun(); // Error - function redefined (because only return type is different) #include <iostream.h> class Maths

{ public: { } { int volume(int i) return(i*i); double volume(double j,int k)

return(j*k); } long volume(long l,int x,int y) { return(l*x*y); } };

Operator Overloading: Operator overloading concept where operator overloaded. In general operator will be applied on variables or on constant but in operator overloading operator use as the name of function and operator applied on object.Types of operator who overload are: overload plus subtract overload object and primitive data type overload assignment operator overload logic operator overload conversion operator overload pointer operator overload address of operator overload unary operator overload bracket operator overload square bracket overload cast operator overload comma operator overload new operator overload delete operator overload ostream istream operator overload operator with friend overload with friend function overloading Dereference operator custom extractor custom inserter enum operator

#include <iostream> using namespace std; class Op_overload { int x, y, z; public:

Op_overload() { x = y = z = 0; } Op_overload(int i, int j, int k) { x = i; y = j; z = k; } Op_overload operator+(Op_overload op2); // op1 is implied Op_overload operator=(Op_overload op2); // op1 is implied Op_overload operator-(Op_overload op2); // op1 is implied void show() ; }; Op_overload Op_overload::operator-(Op_overload op2) // subtraction overload . { Op_overloadtemp_store; temp_store.x = x - op2.x; temp_store.y = y - op2.y; temp_store.z = z - op2.z; returntemp_store; } Op_overload Op_overload::operator+(Op_overload op2) // addition overload. { Op_overloadtemp_store; temp_store.x = x + op2.x; temp_store.y = y + op2.x; temp_store.z = z + op2.z; returntemp_store; } Op_overload Op_overload::operator=(Op_overload op2) // assignment overload . { x = op2.x; y = op2.y; z = op2.z; return *this;

// Show X, Y, Z coordinates. void Op_overload::show() { cout << x << ", "; cout << y << ", "; cout << z << "\n"; } int main() { Op_overload a(10, 20, 30), b(100, 100, 100), c; cout << "value of a: "; a.show(); cout << "value of b: "; b.show();

c = a - c; cout << "a - c: "; c.show(); cout << "\n"; return 0;

} OUTPUT:

value of a: 10, 20, 30 value of b: 100, 100, 100 a - c: 10, 20, 30

Dynamic polymorphism where an entity can modify its form depending on the situation. A function is dynamic polymorphism when one function can have more then one form and the call of various form can be resolved at run time dynamically or at the time of execution. The term late binding refers to the functions resolution at run-time . Late binding give more the flexibility of the program . Virtual Function: A function which become virtual function then use virtual keyword. a virtual function is a member function which is defined in base class and then redefine for other derived classes, and the redefined virtual function will always called by the compiler for an object of the corresponding derived class, even if called by pointer or reference to a base class of the object to that function.

A class that declares or inherits a virtual function is called a polymorphic class.

#include <iostream> using namespace std; class base { public: { void display() cout<<"\n Display base "; } virtual show() { cout<<"\n show base "; } };

class derived:public base { public: void display() { cout<<"\n Display derived "; } void show() { cout<<"\n show derived "; } }; int main() { base b; derived d; base *bptr; cout<<"\n bptr points to base\n"; bptr=&b; bptr->display(); //calls base display bptr->shoe(); //calls base show cout<<"\n bptr points to derived \n"; bptr=&d; bptr->display(); // calls base display bptr->show(); //calls derived show is virtual return 0; } OUTPUT: bptr points to base Display base show Base bptr points to derived Display base show derived

Learn C++ in Easy Way


1. An Introduction To c++ 2. Advantages And Disadvantages Of c++ 3. Difference Between c And c++ 4. A Simple Hello Program In c++

5. Variables And Constants In c++ 6. Operators In c++ 7. Statements In c++ 8. Classes In c++ 9. A Program Of Class With Two Objects 10.Inheritance In C++ 11.A Program On Single Inheritance 12.A Program On Multilevel Inheritance 13.Program Of Hierarchical Inheritance 14.Concept Of Polymorphism 15.Program Of Function Overloading An Introduction To C++
C++ is an extension to C programming Language. It is developed by Bjarne Stroustrup in 1980 at AT & T Bell Laboratories. C++ is created as a bridge between Object Oriented Programming Language and C. C++ is an object oriented programming language. C++ fully support Object Oriented Programming language with 4 main concept encapsulation, data hiding, inheritance, and polymorphism. C++ is also called a high level language. C++ programs are reusable and extensible; existing code is easily modifiable without actually having to change the code. C++ also called superset of C. C programs can be run on C++ Compiler. C language uses structure programming language while C++ uses the concept of object oriented programming language. C++ mainly focuses on Classes and Objects. History Of C++ C++ was designed for the UNIX system environment. With C++ programmers could improve the quality of code. Before C++, C was a programming language developed at Bell Labs. There are several versions of the C++ language, of which Visual C++ is only one. Other include Borland C++, Turbo C++ etc. C++ supports multiple programming styles. C++ provides more than 30 operators, almost all the operators can be overloaded. C++ gives object oriented features to C. C++ has many new keywords, such as new and class, that may be used in a C program as identifier. Structure Of C++ Program Include Files Class Declaration

Member Function Definitions Main Function Program

Difference Between C And C++


1. C is not an object oriented language (C is a procedural programming language), while C++ is an object oriented language. 2. In C we use scanf () as standard input function, while in c++ we use cin>> for input. like this for output in c we use printf() while in c++ we use cout<< as a output function. 3. C does not have the concept of classes and object. 4. C does not have namespaces while C++ have. 5. Function overloading is not supported by C. C++ supports function overloading. 6. C does not have reference variables while C++ uses reference variables. 7. C++ supports operators overloading, C does not support. 8. C have top down approach while C++ have bottom up approach. 9. Data is not structured in C while data is structured in C++. 10. In C #include<stdio.h> is used as header file, but in C++ #include<iostream.h> is used as header file. 11. C does not support C++ programs but C++ support the C program. 12. C is low level language while C++ is high level language.

13. 14.
#<iostream.h> class reactangle { int a, b; // private by default public : void set_values(int,int); int area() { return(a*b); } }; void rectangle::set_values(int a,int b)

A Program Of Class With Two Objects

{ x=a; y=b; } int main() { rectangle rect,rectb; rect.set_values(3,4); rect.set_value(5,7) cout<<"rect area"<<rect.area(); cout<<"rectb area"<<rectb.area(); return0; }

A Program For Single Inheritance


#include<iostream.h> Class A { int a,b; public : void getdata() { cout<<"\n Enter the value of a and b"; cin>>a>>b; } void putdata() { cout<<"\n The value of a is :"<<a<<"and b :"<<b; } }; class B : public A //class is publicly derived from A { int c,d; public : void intdata() { cout<<"\n Enter the value of c and d :"; cin>>c>>d; } void outdata() { cout<<"\n The value of c ;"<<c<<"and d :"<<d; }

}; void main() { B obj; obj.getdata(); //base class member function obj.indata(); //derived class member function obj.putdata(); obj.outdata(); } Output : Enter the value of a and b 2 3 Enter the value of c and d 4 5 The value of a is 2 and b is 3 The value of c is 4 and d is 5

A Program Of Hierarchical Inheritance


#include<iostream.h> Class A { int a,b; public : void getdata() { cout<<"\n Enter the value of a and b"; cin>>a>>b; } void putdata() { cout<<"\n The value of a is :"<<a "and b is "<<b; } }; class B : public A { int c,d; public : void intdata() {

cout<<"\n Enter the value of c and d "; cin>>c>>d; } void outdata() { cout<<"\n The value of c"<<c"and d is"<<d; } }; class C: public A { int e,f; public : void input() { cout<<"\n Enter the value of e and f"; cin>>e;>>f } void output() { cout<<"\nthe value of e is"<<e"and f is" <<f; } void main() { B obj1 C obj2; obj1.getdata(); //member function of class A obj1.indata(); //member function of class B obj2.getdata(); //member function of class A obj2.input(); //member function of class C obj1.putdata(); //member function of class A obj1.outdata(); //member function of class B obj2.output(); //member function of class A obj2.outdata(); //member function of class C } Output : Enter the value of a and b 3 4 Enter the value of c and d

6 8 Enter the 9 4 Enter the 1 8 the value is 4 the value 8 the value is 4 the value 8

value of a and b value of e and f of a is 3 and b of c is 6 and d is of a is 9 and b of e is 1 and f is

Concept Of Polymorphism In C++


In the word Polymorphism 'Poly' means 'Many'. Polymorphism is one of the features of oops. It simply means one name many forms. The concept of polymorphism is implemented using overloaded function and operator. Polymorphism is a mechanism to use a single name with multiple form.

There are two types of polymorphism Compile Time Polymorphism (Function Overloading , Operator Overloading) Run time Polymorphism (Virtual Function)

Compile Time Polymorphism : In this form of polymorphism the selection of the function invocation is done on compile

time. This is also called early binding or static binding. This can be achieved by two ways : Function Overloading Operator Overloading

Runtime Polymorphism : If the member function is selected when the program is running then it called Runtime Polymorphism. This is also called late binding or dynamic binding. Runtime Polymorphism achieve the concept of Virtual Function. Function Overloading : Function overloading means multiple functions of same name with different arguments. C+ + allows functions to be overloaded, that is the same function to have more than one definition. Operator Overloading : Operators are similar to functions they take operands and return a value. For Example : the + operator can be used to add two integers, two reals or two addresses. Virtual Function : Virtual function is a member function of a class, whose functionality can be over-ridden in its derived classes. It can be used with virtual keyword. Virtual member functions are resolved during run-time. This mechanism is known as dynamic binding. The non-virtual member functions are resolved at compile time. This mechanism is called static binding.

Program Of Function Overloading


#include<stdio.h> void myfunction(int a) { cout<<"a is "<<a; //overload myfunction void myfunction(int a, int b) { cout<<"a is"<<a; cout<<"b is"<<b; } //overload myfunction again void myfunction(int a, double b) { cout<<"a is"<<a; cout<<"b is"<<b; } void main() { myfunction(12); //calls myfunction(int)

myfunction(10,34) //calls myfunction(int, int) myfunction(67,123.45) //calls myfunction(int, double) } Output : a is 12 a is 10 b is 34 a is 67 b is 123.45

C++ Basic's Examples


1. Program Of Swapping In C++ 2. Program To Print Digits Of Number 3. Program To Find Out Whether Number Is Prime Or Not 4. Program Of Fibonacci 5. Program Of Array 6. Program Of Pointer 7. Program To Calculate The Area Of Circle, Rectangle And Triangle 8. Convert To Upper Case 9. Demonstration Of Private And Public 10.Largest Number 11.Single Inheritance 12.Multilevel Inheritance

13. Multiple Inheritance 14. Program Of Swapping in C++

#include<stdio.h> #include<conio.h> void main() { int a, b ; cout<<"\n Enter two values"; cin>>a>>b; cout<<"value of a =" <<a<< "and b ="<<b; a=a+b; b=a-b; a=a-b; cout<<"\n value after swaping"; cout<"\n value of a="<<<a; cout<<"\nvalue of b="<<b; } output : Enter two values 12 23 value of a =10 and b =23 value after swappingvalue of a=23 value of b=12

A program to input any number and write all the digits in words
#include<stdio.h> #include<conio.h> void main() { int num,a; cout<<"\n Enter the number"; cin>>num; while(num!=0) { a=num%10; num=num/10; switch(a) { case 1 :cout<<"one"; break; case 2 :cout<<"two"; break; case 3 :cout<<"three"; break; case 4 :cout<<"four";

break; case 5 :cout<<"five"; break; case 6 :cout<<"six"; break; case 7 :cout<<"seven"; break; case 8 :cout<<"eight"; break; case 9 :cout<<"nine"; break; case 10 :cout<<"zero"; break; } } }

OUTPUT: 396 Three nine six Program To Check Whether The Number Is Prime Or Not Using C++
#include<stdio.h> #include<conio.h> void main() { int num,a=1; cout<<"\n Enter the number"; cin>>num; for(int i=2;i<num/2;i+ +) { if(num%i==0) p=p*0; else p=p*1; } } if(p!=0) cout<<"\n number is prome";

else cout<<"\n number is not prime"; }

output: Enter the number 6 number is not prime Program Of Fibonacci Series In C++
#include<stdio.h> #include<conio.h> void main() { int sum,f1,f2,n; f1=o; f2=1; cout<<"\n Enter the range"; cout<<f1<<"/t"<<f2; cout<"\n< the series is"; for(int i=2;i<=n;i++) { sum=f1+f2; cout<< fib<<"/t"; f1=f2; f2=sum; } }

output : Enter the range 12 0 1 1 2 3 5 8 13 21 34 55 89 A Simple Array Example Using C++


#include<stdio.h> #include<conio.h> int main() { int myarray[5];

int i; for(i=0;i<5;i++) { cout<<"Enter the value for array"["<<i<<"]; cin>>myarray[i]; } for(i=0;i<5;i++) cout<<i<<" : "myarray[i]<<"\n;" return 0; }

output : Enter the value of array[0] 3 Enter the value of array[1] 6 Enter the value of array[2] 9 Enter the value of array[3] 12 Enter the value of array[4] 15 0 :3 1:6 2:9 3:12 4:15 Program Of Pointer In C++
#include<iostream.h> int main() { int firstval=5, secondval=15; int *p1,*p2; p1=&firstval; //p1=address of firstval p2=&secondval; //p2=address of secondval

*p1=10; //value pointed y p1=10 *p2=*p1; //value pointed y p2=value pointed y p1 p1=p2; //value of pointer is copied *p1=20; //value pointed by p1=20 cout<<"firstval is"<<firstval; cout<<"secondval is"<<secondval; return 0; }

output : first value is 10 second value is 20 Program To Calculate Area Of Rectangle, Circle, Triangle
#include<stdio.h> void main(); void area_circle(); void area_rect(); void area_tri(); void main() { int option; { do menu(); cin>>option; do { menu(); cin>>option; switch(option) { case 1: area_circle(); break; case 2: area_rect(); break; case 3: area_tri();

break; } } while(option>3); } void menu() { cout<<"\n Menu"; cout<<"\n 1: Area of circle"; cout<<"\n 2: Area of rectangle"; cout<<"\n 3: Area of trangle"; cout<<"\n 4 or greater :Exit"; cout<<"\n Eneter your choice"; } void area_circle() { int r; cout<<"\n Enter radius"; cin>>r; float area=3.14*r*r/4; cout<<"\n area of circle"<<area; } void area_rect() { int a,b; cout<<"\n enter sides"; cin>>a>>b; int area=a*b; cout<<"\narea of rectangle"<<area; } void area_triangle() { float s,a,b,c; cout<<"\n enter sides"; cin>>a>>b>>c; s=(a+b+c)/2 float area=s*(s-a)*(sb)*(s-c); cout<<"\n area of triangle"<<area; }

Output : Menu

1 : Area of circle 2 : Area of rectangle 3 : Area triangle 4 or greater Exit Enter your choice 1 enter radius 4 Area of circle 12.56 Program To Convert An Input Lower Case In Upper Case
#include<iostream.h> void main() { char str[20],*s; cout<<"\n enter the string"; cin>>str; s=str; while(*s!='\0') { if(*s>=97&&*s<=122) *s=*s-32; *s++ } cout<<"\n string is upper case"<<str; }

output :Enter the string computer string in upper COMPUTER

Demonstration Of Private And Public in C++


#include<stdio.h> class demo { private : int x,y; public : int a,b; void getdata(); void putdata(); }; void demo::getdata() { cout<<"\n Emnter the value of x and y"; cin>>x>>y; cout<<"\n Enter the value of a and b"; cin>>a>>b; } void demo::putdata() { cout<<"\n Enter the value of x amd y"; cout<<"\n Enter the value of a and b"; } void main() { demo d; d.getdata(); cout<<"\n the entered values are"; d.putdata(); d.a=10; d.b=20; cout<<"\n The value after moderation are"; d.putdata(); }

Output : Enter value of x and y 23 79 Enter value of a and b

200 100 The entered values are the value of x is 23 and y is 79 the value of a is 200 and b is 100 he value after moderation the value of x is 23 and y is 79 the value of a is 10 and b is 20 Program For Finding Largest Number in C++
#include<stdio.h> class num { int a,b,c; public : void input(void); void largest(void); void smallest(void); }; void num::inputdata(void) { cout<<"Input value of a "; cin>>a; cout<<"Input value of b"; cin>>b; cout<<"input value of c"; cin>>c; } void number :: largest(void) { if(a>b) { if(a>c) cout<"\n largest value"<<<a; else cout<<"\n largest value"<<c; } else { if(b>c) cout<<"\n largest value"<<b; else

cout<<"\n largest value"<<c; } } void num::smallest(void) { if(a<b) { if(a<c) { cout<<"\n smallest number"<<a; else cout<<"\n smallest number"<<c; } else { if(b<c) cout<<"\n smallest numeber"<<b; else cout<<"\n smallest number" <<c; } } int main() { num n; n.input(); n.largest(); n.smallest(); return 0; }

output : input value of a=15 input value of b=34 input value of c=30 largest value is 34 smallest value is 15 Program Of Single Inheritance
#include<stdio.h>

class A { int a1,a2; public : void getdata() { cout<<"\n Enter value of a1 and a2"; cin>>a1>>a2; } void putdata() { cout<<"\n value of a1 is" <<a1"and a2 is"<<a2; } }; class B: public A //class B is publicly derived by class A { int b1,b2; public : void indata() { cout<<"\n Enter the value of b1 nad b2"; cin>>b1>>b2; } }; void main() { B b; b.getdata(); //base class member function b.indata(); //derived class member function b.putdata(); b.outdata(); }

output : enter value of a1 and a2 2 3 enter value of b1 and b2

4 5 the value of a1 is 2 and a2 is 3 the value of b1 is 4 and b2 is 5 Program For Multilevel Inheritance Example Using C++
#include<stdio.h> class A { int a1,a2; public : void getdata() { cout<<"\n Enter value of a1 and a2"; cin>>a1>>a2; } void putdata() { cout<<"\n value of a1 is" <<a1"and a2 is"<<a2; } }; class B: public A //class B is publicly derived by class A { int b1,b2; public : void indata() { cout<<"\n Enter the value of b1 nad b2"; cin>>b1>>b2; } void outdata() { cout<<"\n the value of b1 is" <<b1 "and b2 is:<<b2; } }; class C: public B { int c1,c2; public void input()

{ cout<<"\n enter the value of c1 and c2"; cin>>c1>>c2; } void output() { cout<<"\nvalue of c1 is"<<c1"and c2 is"<<c2; } };void main() { C obj obj.getdata(); //member function of class A obj.indata(); //member function of class B obj.input(); //member function of class C obj.putdata(); //member function of class A obj.outdata(); //member function of class B obj.output(); //member function of class C }

output : Enter value of a1 and a2 3 4 Enter value of b2 and b2 6 7 Enter value of c1 and c2 8

9 the value of a1 is 3 and a2 is 4 the value of b1 is 6 and b2 is 7 the value of c1 is 8 and c2 is 9

Program For Multiple Inheritance Example Using C++


#include<stdio.h> class A { int a1,a2; public : void getdata() { cout<<"\n Enter value of a1 and a2"; cin>>a1>>a2; } void putdata() { cout<<"\n value of a1 is" <<a1"and a2 is"<<a2; } }; class B { int b1,b2; public : void indata() { cout<<"\n Enter the value of b1 nad b2"; cin>>b1>>b2; } void outdata() { cout<<"\n the value of b1 is" <<b1 "and b2 is:<<b2; } }; class C: public A,public B { int c1,c2; public void input()

{ cout<<"\n enter the value of c1 and c2"; cin>>c1>>c2; } void output() { cout<<"\nvalue of c1 is"<<c1"and c2 is"<<c2; } }; void main() { Cc c.getdata(); //member function of class A c.indata(); //member function of class B c.input(); //member function of class C c.putdata(); //member function of class A c.outdata(); //member function of class B c.output(); //member function of class C }

Output : Enter the value of a1 and a2 5 4 Enter the value of b1 and b2 8 7 enter the value of c1 and c1 9 3 The value of a1 is 5 and a2 is 4

The value of b1 is 8 and b2 is 7 The value of c1 is 9 and c2 is 3 C++ Interview Questions And Answers

Page 1
Ques: 1 Question : what is the difference between parameter and argument? Ans: Diff b/w parameter and argument is : Argument bassically is one of the following > An Expression in the comma-separated list in a function call. > A sequence of one or more preprocessor tokens in the comma-separated list in a macro call. > Its represent the value which you pass to a procedure parameter when you call the procedure. The calling code supplies the arguments when it calls the procedure. > It is something passed into a function(value), whereas a parameter is the type of data plus the name. Parameter bassically is one of the following > An object that is declared in a function declaration or definition. > An identifier b/w the parentheses immediately following the macro name in a macro definition. > It is represent a value that the procedure expects you to pass when you call it. The procedure's declaration defines its parameters. This example explains the difference b/w a parameter and an argument: void function(int x, char * rs); //x and rs are parameters template <class Tem> class M {}; //Tem is a parameter int main() { char c; char *p = &c; func(5, p); //5 and p are arguments M<long> a; //'long' is an argument M<char> another_a; //'char' is an argument return 0; } Ques: 2 What is the difference between class and structure? Ans: Diff b/w Class and Structure is : Class is difined as>Class is a successor of Structure. By default all the members inside the class are private. >Class is the advanced and the secured form of structure. >Classes are refernce typed. >Class can be inherited.

>In Class we can initilase the variable during the declaration. >Class can not be declared without a tag at the first time. >Class support polymorphism. Structure difine as : > In C++ extended the structure to contain functions also. All declarations inside a structure are by default public. > Structures contains only data while class bind both data and member functions. > Structure dosen't support the polymorphism, inheritance and initilization. > Structure is a collection of the different data type. > Structure is ovrloaded. > Structures are value type. > Structure can be declared without a tag at the first time Ques: 3 What is the difference between an object and a class? Ans: Class and Objects are diff but related concepts. Every objects belogs to the class and evry class have a one or more related objets. Class are: > A Class is static. > A class combination of data(called data members)and functions(called member functions). > Class is a userdefined datatype with data members and member functions. > Classe defines object. > One class can define any no of Object. > Class is a template(type) or blue print its state how objects should be and behave. Object are: > Object is an instance of a class while a class can have many objects. > Object is a dynamic. > Objects are the basic runtime entities in an object oriented sysyem. > Data and function which combine into a single entity is called object. > Objects are instances of classes which identifies the class propeties. > Object can't define classes. > Object can created and destroyed as your necessity. > Object is defined as a s/w construct which binds data and logic or methods(functions) both. Ques: 4 Difference between realloc() and free()? Ans: Diff b/w realloc() and free(): realloc(): > It is used to free the memory in the program. > This function is used to resize memory. > realloc() means it giving string variables into the existed memory free(): > Basically It is a macro. Macro used to deallocate memory. > free() function is used free the memory which is allocated by malloc(),calloc() functions. > free() means it empties the array. Ques: 5 What is a template? Ans: Templates is defined as : > It is a framework for web pages and sites. > Its type of model or standard for making comparisons. > It is a feature of the C++ programming language its allow functions and classes to be operate with generic types.

> It is a tool for enforcing a standard layout and look and feel across multiple pages or within content regions. > Its a model or pattern used for making multiple copies of a single object. Ques: 6 What is virtual constructors/destructors? Ans: virtual constructors/destructors : Virtual destructors It is a Bassically same as vertual fuction, Its commonly used with inheritance. Since an abstract class must contain a pure virtual method that has to be overridden, a lot of developers commonly declare their destructors pure virtual, since a destructor is sure to be implemented in every subclass. Constructors cannot be virtual. Declaring a constructor as a virtual function is a syntax error. There is no virtual constructor coz virtual thing is in run time n constructor is compile time thing. Ques: 7 What is the difference between operator new and the new operator? Ans: Many diff are there : Operator new is bassically just like malloc and new is the conventinally new in C++. The "New" operator allocates a new instance of an object from the heap, Its utilising the most appropriate constructor for the arguments passed. This is Like many operators in C++, The "New" operator for a particular class can be overriden, Although there is rarely a need to do so. "Operator new" is the mechanism for overriding the default heap allocation logic. Ans: Operator new() use for the Operator overloading but New Operator for memory allocation. Ques: 8 Difference between "C structure" and "C++ structure". Ans: Many diff are there : >Structure in C defines as limited to within the module and cannot be initialized outside but Structure in C++ can initialize the objects anywhere within the boundaries of the project. > C++ have a many methods((Procedures) but in C no methods are there. > By default C structure are Public and C++ structure are private . > C does not support Methods inside structure but C++ does. > In C++ structure we can add functions but in C structure we can't. > In C++, structure behaves like class like can add function, and can use properties on class as inheritance, virtual,etc, But in C, structure we can have only data member but not functions. > Structures in c++ doesnot provide datahiding but a class provides. > classes support polymorphism, But Structures don't. Ques: 9 What is the difference between "overloading" and "overriding"? Ans: Many Diffreces are thereOverloading a method (or function) in C++ is the ability for functions of the same name to be defined as long as these methods have different signatures (different set of parameters). Method overriding is the ability of the inherited class rewriting the virtual method of the base class. overridding is runtime polymorphism while overloading is compile time polymorphism. Ques: 10 Difference between a "assignment operator" and a "copy constructor"

Ans: many diff are there : > Assignment operator assign the object of one object to another aftr the 1st object is fully created but in copy constructor it assign the value of one object to another at the time of its creation . > The copy constructor is use for initialising a new instance from an old instance, And is called when passing variables by value into functions or as return values out of functions. but in Assignment operator is used to change an existing instance to have the same values as the rvalue, which means that the instance has to be destroyed and re-initialized if it has internal dynamic memory. > Copy constructor copies a existing object to a non existing object, which we are going to create. Assignment operation can happen between two existing objects. > The copy constructor is creating a new object. But in The assignment operator has to deal with the existing data in the object. > Copy constructor creates shallow copy but in assignment operator creates deep copy. > The copy constructor is called at initialising the object but the assignment operator is used to assign one object to another. > Copy constructor donot return anything. But in Assignment operator returns object of same type. > The copy constructor initializes uninitialized memory, But in assigenment operator starts with an existing initialized objects. > Copy constuctor initialize the object with the another object of same class But assignment operator can be called on objects of different classes . Ques: 11 What is the advantage of function overloading according to users point of view? Ans: We know that function name is same. But each time we are writing code for each function. In this case it is advantageous than normal function. Ans: waste site Ques: 12 What is difference between visual c++ & ANSI c++ ? Ans: Visual C++ is probably the most popular favored compiler, because of it's history of quality and stablity.But in ANSI C++ is a less popular, but is a much more powerful and robust compiler. The IDE is also a lot more powerful than MSVC. Ques: 13 What is the difference between far pointer and near pointer? Ans: Many diff are there : > A normal pointer can only point to the main memory location, But the far pointer can have an address of any location of ur memory even seconday one also. > A far pointer is used to access a location which is outside current segment. > Near pointers are fully recognised and evaluated for their entire width. But in Far pointers only allow normal operations to be done to their offset amount and not the segment or paragraph amount. Ques: 14 What are virtual functions? Ans: virtual functionsdefines as :

> C++ virtual function is a member function of a class, whose functionality can be over-ridden in its derived classes. The whole function body can be replaced with a new set of implementation in the derived class. > A virtual function is a member function which we may redefine for other derived classes, And can ensure that the compiler will call the redefined virtual function for an object of the corresponding derived class, Even if we call that function with a pointer or reference to a base class of the object. > A virtual function is a member function of a class, which functionality can be over-ridden in its derived classes. It is one that is declared as virtual in the base class using the virtual keyword. > C++ virtual function properties are: * A member function of a class. * Declared with virtual keyword. * Usually has a different functionality in the derived class. * A function call is resolved at run-time. Ques: 15 What is RTTI? Ans: RTTI bassicaly Run Time Type Information. It Certain language features to work a limited amount of information about types is required at runtime. This is the Run Time Type Information or RTTI. Ques: 16 What happens to the member function in the class when copy constructor is invoked? Ans: First of all we want to tell you that only the member function have the athourity to invoke any other member function.But cunstructor have a diff property, is that it used to initialise the values to data members. and they are constant and it cannot be invoked any other constuctor. If they are copied compiler should not understand or didnot diffrentiate that what is member function and what is constructor, so ambiquity will be raised. Ques: 17 What is the difference between block structured language and highly block structured language Ans: Block Structure Langguage Bassically a normal programming language in which sections of source code contained within pairs of matching delimiters such as "" and "" (e.g. in C) or "begin" and "end" (e.g. Algol) are executed as a single unit. Its A class of high-level languages in which a program is made up of blocks which may include nested blocks as components, such nesting being repeated to any depth. Ques: 18 How will you detect if there is memory leak in your C++ program? Ans: Some time before we have got a some problem of detecting memory leaks in our code, and we didn't afforrd the rates of a brittle software package to do that. It's fairly simple to redefine malloc() and free() to your own functions, to track the file and line number of memory leaks. But what about the new() and delete() operators? It's a little more difficult with C++, if we want to figure out the exact line number of a resource leak. If we are using new and delete operator, We can overload both the operators and can count number off heap allocation and deallocation. You can also get the __FILE__ and __LINE__ to get to know the file name and line number. Now the new and delete of a memory location should be in pair and if its not there is a memroy leak. By using line and file utility you can reach upto the exact location. Ques: 19 What was the most difficult debug you have ever done?

Ans: whenever any application get hanged, & we don't know even from wherewe should start debuging....this can be the most difficult . Ques: 20 What is the use of new operator? Ans: In C++ New Operator used to allocate the memory for the object on HEAP. It allocates the memory of size equal to the object of size, The new operator will return NULL or throw an exception on failure. It provides dynamic storage allocation. Its syntax for an allocation expression containing the new operator is: >>-+----+--new--+---------------------+--+-(--type--)-+---------> '-::-' '-(--argument_list--)-' '-new_type---' >--+-------------------------+--------------------------------->< '-(--+---------------+--)-' '-initial_value-'

C++ Interview Questions And Answers

Page 1
Ques: 1 can derived clss exception also be caught by the catch block? Ans: No Ques: 2 What Is a B-Tree? Ans: The B-tree was invented in 1972 by R. Bayer and E. McCreight, and was designed from the start to create shallow trees for fast disk access. Shallow trees have few levels, We have to seek through them fewer times, and therefore they run quickly. Because seeks often require going to disk for the information we need, The performance increase with a shallow tree rather than a deeper tree can be substantial. B-trees are a powerful solution to the problem of disk-based storage; virtually every commercial database system has used variations on a B-tree for years. A B-tree consists of pages. Each page has a set of indices. Each index consists of a key value and a pointer. The pointer in an index can point either to another page or to the data you are storing in the tree. Thus, every page has indices that point to other pages or to data. If the index points to another page, the page is called a node page; If the index points to data, the page is called a leaf page. Ques: 3 What is Parsing Numeric Expressions? Ans: Numeric expressions are generally represented by the infix notation, In which the operator is placed between the operands and parentheses are used where necessary to indicate the order in which the operators are applied to the Expressions. Numeric expressions are best computed using a postfix notation also called reverse polish notation, In which the operator is placed after its two operands and parentheses are not required. Ques: 4 What is the Parsing? and tell me how many types of Parsing?

Ans: Parsing is a generic operation that identifies legal expressions and breaks them up into a form suitable for further processing. Parsing has applications in many different fields such as computer science, Interpreting human language, and so on. The main goal of parsing is to check the validity of an expression and make more sense out of it. The term grammar is commonly used in programming languages to identify legal expressions. There are two approaches commonly used during parsing of these two methods : > Top-down approach: This method looks at the program first, and recursively identifies parts that are eventually matched to the input expression. > Bottom-up approach: This method looks at the input expression and combines the pieces of the expression to make a legal program from it. Ques: 5 What is Quadratic Probing? Ans: The Performance problem encountered by linear probing is caused by the cluster buildup That occurs as a result of the probing sequence. Quadratic probing uses a different sequence to avoid primary clustering. Ques: 6 What is an Bucket Addressing? Ans: The Bucket Addressing Technique is similar to chaining in that collision resolution is performed by using additional space. Whenever instead of using linked lists, We make use of buckets. A bucket can be defined as a block of space that can be used to store multiple elements that hash to the same position. In this method, We must give the buckets a fixed size; The Choice of this size can sometimes be tricky. Collisions are still possible because you may fill a bucket completelyin which case the key must be stored somewhere. This storage location can be an available bucket or an overflow area. A variation can be used to eliminate the need for buckets with fixed size: We can allow each bucket to contain a pointer to a dynamically allocated array. Ques: 7 What is the chaining? Ans: The Chaining technique basically looks at the hash table as an array of pointers to linked lists. Each slot in the hash table is either empty or simply consists of a pointer to a linked list. You resolve collisions by adding the elements that hash to the same slot to the linked list to which that slot points. At the same time, deletions are easy, You simply delete elements from the linked list. Ques: 8 What is the Hash Function? Ans: The hash function is an important part of the hashing technique. This function is used to transform the keys into table addresses. The hash function we choose should be easy to compute and should be able to transform the keys into integers in the range 0 to TR-1. Because most of the commonly used hash functions are based on arithmetic operations, We should convert the keys to numbers on which arithmetic operations can be performed. Ques: 9 What Is Recursion?

Ans: Recursion is when a thing refers to itself or to an image just like itself. For a function, recursion means that the function calls itself. For an object,Recursion is when the object refers to things like itself by means of a pointer or a reference. Often, recursive structures and recursive functions go hand in hand. The best way to do many of the common operations on recursive structures is to use a recursive function. Ques: 10 What is the Heap Operations? Ans: A Heap is a sequence in which the element with the largest value is always the first element in the sequence. Elements are pushed into and popped out of the heap only at the front of the sequence. The STL priority queue is usually implemented as a heap. The Standard Library provides two heap-to-sequence conversion operations and two heap element access operations. Ques: 11 Whats the requirement of Input Itrator? Ans: An input iterator is an iterator that must satisfy the following set of requirements which is there : > Default Constructible: The iterator must have a default constructor so that it can be created without initializing it to any particular value. When an input iterator is created using its default destructor, It is an invalid iterator. It remains invalid until it is assigned a value. > Assignable: The iterator must have a copy constructor and an overloaded assignment operator. These features allow for copying and assigning values to iterators. > Equality Comparable: The iterator must have an overloaded equality operator == and an inequality operator !=. These operators allow for the comparison of two iterators. Ques: 12 What are The Multimap Container? Ans: A Multimap is similar to a map except that elements can have duplicate keys. Even the multimap class has a similar class definition to the map container class, W ith some exceptions. It has no subscripting operators because there may be more than one element that has the same key value. The insertion operation is always okay because duplicate keys are allowed. Ques: 13 What is the The Deque Container? Ans: A Deque is bassically a type of vector .It is like a double-ended vector, It inherits the vector container classs efficiency in sequential read and write operations. But in case of addition, the deque container class provides optimized front-end and back-end operations. These type of operations are same as implemented they are in the list container class, where memory allocations are engaged only for new elements. This feature of the deque class eliminates the need to reallocate the whole container to a new memory location, as the vector class has to do. Even deques are ideally suited for applications in which insertions and deletions take place at either one or both ends, and for which sequential access of elements is important. Ques: 14 What is the mean of Memory Leaks?

Ans: The Memory Leak is bassically a term of the memory . The Term memory leak is quite popular in the industry, But it isnt often explained. Heres the idea: If you allocate memory using new and fail to reclaim that memory using delete, the memory is irretrievably lost until your program ends. It is as if the memory leaked out of your program. Ques: 15 What is the mean of Utility Classes? Ans: A Utility class is bassicaly a class that contains grouped functionality. But no persistent data members or attributes. Although utility classes are not part of standard C++, some programmers like to create them. The UML offers support for them. The purpose of a utility class is to take a set of functionality and group them together in a common class. There is no need to create an instance of this class because each function in the class is declared static: We can simply use the functions contained in the class by fully qualifying the desired function name. Ques: 16 What is the Realization? Ans: A Realization is a type of relationship , It is a relationship between two model elements, in which one model element or the client realizes the behavior that the other model element or the supplier specifies. A realization is displayed in the diagram editor as a dashed line with an unfilled arrowhead towards the supplier. Ques: 17 What is the class diagram ? Ans: Class diagrams are bassically use for explain the classes in the terms of diagram.It serve two purposes: > to represent the static state of classes and > to exploit. the relationships between those classes. In the early stages of the software development life cycle, it is important to note that the class diagram model attempts not only to define the public interface for each class but to define the associations, aggregations, and generalizations defined between the individual classes. Ques: 18 Whats the use of Interaction Diagrams? Ans: Interaction diagrams are bassicaly used for the mdels behavior when models are work in the saeveral objects in a use case. They are reprasented how the objects collaborate for the behavior. Interaction diagrams do not give a in depth representation of the behavior. If we want to know what a specific object is doing for several use cases use a state diagram. Then we got particular behavior over many use cases or threads use an activity diagrams. Ques: 19 What is the Interaction Diagrams? Ans: Interaction diagrams is bassicaly a type of model . Models behavior of use cases by describing the way groups of objects interact to complete the task. And The two kinds of interaction diagrams are sequence and collaboration diagrams.In this case that can dramatically improve the documentation and understanding of the intraction. Ques: 20 What are the Limitations of CRC Cards? Ans: CRC Cards are very useful thing but its also have Many limitations which are there : > its a inherent limitations > Its also dont capture the interrelationship among classes. > the nature of the collaboration is not modeled well.

> CRC cards also dont capture attributes. > CRC cards do not capture this information.

C++ Subjective Questions with Answers Q1. What is Polymorphism? Ans: Polymorphism is phenomena by which we can make make a method for reuse. Polymorphism is an object oriented term. Polymorphism may be defined as the ability of related objects to respond to the same message with different, but appropriate actions. In other words, polymorphism means taking more than one form. Polymorphism leads to two important aspects in Object Oriented terminology - First one is function Overloading and second is function Overriding. Overloading is the practice of supplying more than one definition for a given function name in the same scope. The compiler is left to pick the appropriate version of the function or operator based on the arguments with which it is called. Overriding refers to the modifications made in the sub class to the inherited methods from the base class to change their behavior. Q2. What is Operator overloading? Ans: When an operator is overloaded, it takes on an additional meaning relative to a certain class. But it can still retain all of its old meanings. Examples: 1) The operators >> and << may be used for I/O operations because in the header, they are overloaded. 2) In a stack class it is possible to overload the + operator so that it appends the contents of one stack to the contents of another. But the + operator still retains its original meaning relative to other types of data. Q3. What are Templates ? Ans: C++ Templates allow u to generate families of functions or classes that can operate on a variety of different data types, freeing you from the need to create a separate function or class for each type. Using templates, u have the convenience of writing a single generic function or class definition, which the compiler automatically translates into a specific version of the function or class, for each of the different data types that your program actually uses. Many data structures and algorithms can be defined independently of the type of data they work with. You can increase the amount of shared code by separating data-dependent portions from data-independent portions, and templates were introduced to help you do that. Q4. What is the difference between run time binding and compile time binding? Ans: Dynamic Binding:This is also known as "Late Binding".The address of the functions are determined at runtime rather than at compile time. Static Binding:This is also known as "Early Binding" .The address of the functions are determined at compile time rather than at run time. Q5. What is Difference Between C/C++ Ans: 1.In C passing value to a function is "Call by Value" whereas in C++ its "Call by Reference" 2.C does not have a class/object concept. C++ provides data abstraction, data encapsulation, Inheritance and Polymorphism.

3.C++ supports all C syntax. File extension is .c in C while .cpp in C++.(C++ compiler compiles the files with .c extension but C compiler can not!) 4.In C structures can not have contain functions declarations. In C++ structures are like classes, so declaring functions is legal and allowed. C++ can have inline/virtual functions for the classes. c++ is C with Classes hence C++ while in c the closest u can get to an User defined data type is struct and union. Q5. What will be the output of the following code? void main (){ int i = 0 , a[3] ; a[i] = i++; printf ("%d",a[i]) ; } The output for the above code would be a garbage value. In the statement a[i] = i++; the value of the variable i would get assigned first to a[i] i.e. a[0] and then the value of i would get incremented by 1. Since a[i] i.e. a[1] has not been initialized, a[i] will have a garbage value. Q6: Why doesn't the following code give the desired result? Ans: int x = 3000, y = 2000 ; long int z = x * y ; Ans:Here the multiplication is carried out between two ints x and y, and the result that would overflow would be truncated before being assigned to the variable z of type long int. However, to get the correct output, we should use an explicit cast to force long arithmetic as shown below: long int z = ( long int ) x * y ; Note that ( long int )( x * y ) would not give the desired effect. Q7: Why doesn't the following statement work? char str[ ] = "Hello" ; strcat ( str, '!' ) ; Ans: The string function strcat( ) concatenates strings and not a character. The basic difference between a string and a character is that a string is a collection of characters, represented by an array of characters whereas a character is a single character. To make the above statement work writes the statement as shown below: strcat ( str, "!" ) ; Q8: How do I know how many elements an array can hold? Ans: main( ){ int i[32767] ; float f[16383] ; char s[65535] ; } Q9: How do I write code that reads data at memory location specified by segment and offset? Ans: Use peekb( ) function. This function returns byte(s) read from specific segment and offset

locations in memory. The following program illustrates use of this function. In this program from VDU memory we have read characters and its attributes of the first row. The information stored in file is then further read and displayed using peek( ) function. #include <stdio.h> #include <dos.h> main( ){ char far *scr = 0xB8000000 ; FILE *fp ; int offset ; char ch ; if ( ( fp = fopen ( "scr.dat", "wb" ) ) == NULL ) { printf ( "\nUnable to open file" ) ; exit( ) ; } for ( offset = 0 ; offset < 160 ; offset++ ) fprintf ( fp, "%c", peekb ( scr, offset ) ) ; fclose ( fp ) ; if ( ( fp = fopen ( "scr.dat", "rb" ) ) == NULL ) { printf ( "\nUnable to open file" ) ; exit( ) ; } for ( offset = 0 ; offset < 160 ; offset++ ) { fscanf ( fp, "%c", &ch ) ; printf ( "%c", ch ) ; } fclose ( fp ) ; } Q10: Is it possible to have Virtual Constructor? If yes, how? If not, Why not possible ? Ans: There is nothing like Virtual Constructor. The Constructor cant be virtual as the constructor is a code which is responsible for creating a instance of a class and it cant be delegated to any other object by virtual keyword means. Q11: What about Virtual Destructor? Ans: Yes there is a Virtual Destructor. A destructor can be virtual as it is possible as at runtime depending on the type of object baller is balling to , proper destructor will be called. Q12: What is Pure Virtual Function? Why and when it is used ? Ans: The abstract class whose pure virtual method has to be implemented by all the classes which derive on these. Otherwise it would result in a compilation error. This construct should be used when one wants to ensure that all the derived classes implement the method defined as pure virtual in base class.

Q13. What is problem with Runtime type identification? Ans: The run time type identification comes at a cost of performance penalty. Compiler maintains the class. Q14: How Virtual functions call up is maintained? Ans: Through Look up tables added by the compile to every class image. This also leads to performance penalty. Q15: Can inline functions have a recursion? Ans: No. Syntax wise It is allowed. But then the function is no longer Inline. As the compiler will never know how deep the recursion is at compilation time. C++ Interview Questions
Q1:How do you decide which integer type to use? Q2:What should the 64-bit integer type on new, 64-bit machines be? Q3:Whats the best way to declare and define global variables? Q4:What does extern mean in a function declaration? Q5:Whats the auto keyword good for? I cant seem to define a linked list node which contains a pointer to itself. Q6:How do I declare an array of N pointers to functions returning pointers to functions returning pointers to characters? Q7:How can I declare a function that returns a pointer to a function of its own type? Q8:My compiler is complaining about an invalid redeclaration of a function, but I only define it once and call it once. Whats happening? Q9:What can I safely assume about the initial values of variables which are not explicitly initialized? Q10:Why cant I initialize a local array with a string? What is the difference between char a[] = string; and char *p = string; ? Q11:How do I initialize a pointer to a function? Q12:What is Operator, Operand, Expression, Statement in 'C'? Q13: What is polymorphism? Q14:What is operator overloading? Q15:What are templates? Q16:Declare a void pointer. Q17: Declare a function pointer which takes a pointer to char as an argument and returns a void pointer. Q18:Type-define a function pointer which takes a int and float as parameter and returns a float *. Q19:What does the following C statement do? while(*c++ = *d++); assuming c and d are pointers to characters. Q20:How do you call a C module within a C++ module. Q21:What is the difference between run time binding and compile time binding? Discuss. Q22:Compare and contrast C++ and Java. Q23:Why does C/C++ give better run-time performance then Java? Q24:Does C++ come with in-built threading support. Q25:Class A derives B derives C. All have foo(). I cast C to A and call foo(). What happens? Q26:All classes A, B, C have default constructor, foo() that calls parent foo() and allocates 100 bytes to their own private local variable, and a destructor that frees the 100 bytes. I

create a C object and then destroy it. What's the problem? Did all the memory get freed? What if I create C, cast to A, and then destroy it. How would I make sure memory is freed? (destructor must be virtual" and each destructor must call parent destructor)" Q27:What errors are caught at compile time vs link time? Q28:What is the value of "a" after this? int (*a) [10]; a++; Q29: What is wrong with this? main(){ int *ptr; *ptr=10; } Q30:Given int n, i=10, j=20, x=3, y = 100; What is the value of n and y at the end of each of the following expressions? a) n = (i > j) && (x < ++y); b) n = (j - i) && (x < y++); c) n = (i < j) || (y+=i); Q31: int x = 5; int y = 7; What is the value of x and y after the expression y+=x++; Q32:What's the difference between C and C++? Q33:What does Public and Private mean in C++ Q34: Is it possible to keep 2 stacks in a single array, if one grows from position one of the array, and the other grows from the last position. Write a procedure PUSH(x,s) that pushes element x onto stack S, where S is one or the other of these two stacks. Include all necessary error checks Q35:Why would you use: public/private/protected inheritance? Q36:Why does the language not define static virtual functions Q37:Can you make a destructor virtual? Q38: Why would you want a virtual destructor? Q39:How would you print the first 10 characters of a string? Q40:When would you use private inheritance? Q41:How and why would you implement a '<<' operator for a String class? Q42:When would you use a reference? Q43:Why do you want to have virtual member functions? How was "it" done before vmf's came into existence? What was wrong with it? Q44:Why is protected" as bad as ""public""?" Q45:Give one example use of a static member. Q46: Why did new (a new expression) have to be a language-level construct while malloc could be a library function? Q47: What are the advantages and disadvantages of templates over plain old inheritance and heterogenous containers? Q48: What are the problems with a tree-style hierarchy? Q49:Why is iostream better than stdio? (There are umpteen reasons, I'm just talking about the type-safe answer...) Q50:Why would someone want to have RTTI when there are virtual functions? Doesn't that sound contradicting in purpose? Discuss one situation where RTTI could be useful, if you think so.

You might also like