C++ Quick Notes before Interview


C++ Quick Summary for Interview

Topics covered:

  1. Difference between c and c++
  2. Namespace
  3. Default arguments
  4. Inline functions
  5. Reference in c++
  6. Object oriented programming

Abstraction(polymorphism)
Encapsulation
Dependency
Association
Composition
Aggregation
Inheritance(polymorphism)
Packages

7. Static and non-static variables/functions
8. Constructor
Default cons.
Implicit and user-defined Copy cons.
Destructors
9. New /delete and malloc /free
10. Anonymous object
11. Operator overloading
12. Const function and object
13. Mutable
14. Exception handling
15. Templates
16. Inheritance
17. Overriding
18. Run time polymorphism
19. Abstract class
20. Interface
21. Constructor and destructor in inheritance
22. Lishkov’s substitution principle
23. run-time type identification (RTTI)

Difference between c and c++

  1. Loosely typed nature of C and strongly typed  nature of C++

Example:
Int *i=malloc(8);
—In c,it will work fine but in c++,needs typecasting.
int  I;
Char *y;
y=&I;
—works fine in c but problem in c++.

2. Function is getting called based on function name in C, function name + input arguments in C++
—this is because, we have overloading in C++.
Ex:
Void f1()
Void f1(intx)
—works fine in c++, but not in c.

Function overloading
–function name has to be same
–input arguments must differ either by no. of arguments or order of arguments or by type of arguments.

Void f1(int x)— Void f1(int x,int y)
Void f1(int x,char y)—– Void f1(char y,int x)
Void f1(int x)—— Void f1(char x)

3. Features relatively easier to implement in C++ are oo, templates, operator overloading exception handling. This will be tedious to implement in C.

 
Namespace
—to avoid naming conflicts (project may be using 3rd party code)
—-it is for user defined types/variables/functions
Ex:
namespace trytoshowcommonsense
{
int i;
void f1() { printf("ok");
}

struct Device
{};
}

void f1()

{               printf(“I do know c++ gives overloading”);     }

void f1(int x=1, int y=2)

{               printf(“%d %d”,x,y);             }

int main()

{               f1(3,4);
//             f1(); //this will result in error(ambiguous call to f1)

trytoshowcommonsense::f1();//solves the problem
return 0;
}
Default Arguments
—makes input arguments of function optional
—created from right to left, only when arguments are not passed explicitly by programmer.
Ex:
Void f1(int x,int y=2)
{
Pf();
}
Main()
{
F1(3,4); //output=3,4(4,defined by programmer)
F1(3); //output=3,2(2,default)
}

Inline functions
— we can avoid switching costs to the function
i.e. function will now not have an execution context.
I.e. stack frame, prologue ..program counter.. epilogue.
instead the compiler wherever we called the function, will replace it with the body of the function.
–it is only a suggestion to compiler and may not obey.
Ex:
Inline void f1()
{               pf();
}

Pass by reference
–reference is alias name for variables.
–used to conserve memory.
–printing address in c++, is undefined.

struct Device
{
int deviceId;
int status;
};

void acceptDeviceDetails(struct Device d)
{               printf(“pass by value”);
d.deviceId=23;
}

void acceptDeviceviaAdd(struct Device  *const d)
{               printf(“pass by address”);
d->deviceId =24;
}

void acceptDeviceDetailsThruRef(struct Device &e)
{               e.deviceId=25;
printf(“pass by reference”);
}

int main()
{
struct Device d;
acceptDeviceDetails(d);
acceptDeviceDetailsThruRef(d);
printf(“%d”,d.deviceId);
}

Object oriented programming
Encapsulation
–it is a way through which we access data in an organized way.
–class is a unit for encapsulation. Its scope is higher than local but lesser than global.
–class is a user defined data type and template or blueprint of object.
–object is something that has identity.

Generally, in encapsulation we do variables (private) and functions (public).
Static and non-static variables
 
Static
When we precede a member variable’s declaration with static, we are telling the
compiler that only one copy of that variable will exist and that all objects of the class will share that variable. Unlike regular data members, individual copies of a static member variable are not made for each object. No matter how many objects of a class are created, only one copy of a static data member exists. Thus, all objects of that class use that same variable. All static variables are initialized to zero before the first object is created.

When you declare a static data member within a class, you are not defining it. (That is, you are not allocating storage for it.) Instead, you must provide a global definition for it elsewhere, outside the class. This is done by re-declaring the static variable using the scope resolution operator to identify the class to which it belongs. This causes storage for the variable to be allocated. (Remember, a class declaration is simply a logical construct that does not have physical reality.)

class shared {
static int a;
int b;
public:
void set(int i, int j) {a=i; b=j;}
void show();
} ;

int shared::a; // define a
void shared::show()
{
cout << “This is static a: ” << a;
cout << “\nThis is non-static b: ” << b;
cout << “\n”;
}

int main()
{
shared x, y;
x.set(1, 1); // set a to 1
x.show();
y.set(2, 2); // change a to 2
y.show();
x.show(); /* Here, a has been changed for both x and y
because a is shared by both objects. */
return 0;
}

Output:
This is static a: 1
This is non-static b: 1
This is static a: 2
This is non-static b: 2
This is static a: 2
This is non-static b: 1
 
what is non static function
1. non static function is used to expose non static variables to outside world.
2. they need an object to access.
3. they can access everything in the class i.e. static as well as non static.
4. they know “this”.

what is static function.
1. to use static variables to outside world.
2. they dont need an object to access them we can access by object also.
3. they cannot access non static variables of the class directly.
4. they dont know “this”.
what is “this“?
this is a implicit pointer referring to the calling object available only in non static functions of a class.
easy example of this.
if a local variable and an instance variable is with the same name then use this to differentiate instance variable from the local variable.
this->instance variable = local variable.

class Z
{
void freak()
{
A i;
int x =3;
i.f1(this);
}
}

class A
{
public:
void f1(Z*   x)  {    }
}

Constructors.
1.1 create objects conditionally.
1.2 initialize non static variables.
1.3 need may be to allocate memory dynamically to the non-static variables.
1.4 on any object constructor will get called only once.

Ex:
class A
{               int i;

public:
A(int x) { i =x; }
}

main()
{               A OBJ1;
}

what is a copy constructor.
a constructor which gets called when a new object has to be created based on an existing object is called as copy constructor.

system given copy constructor
it will copy the non static variable values from the existing object and copy it to non static variables of the new object.
system given copy constructor is good if the class has non pointer, instance variables.
Problem if the class has got pointer type instance variables, because then two pointers will point to same thing and it will give error in code.

Ex:
#include<stdio.h>
#include<iostream>
using namespace std;
class A
{
public:
A()           {printf("1");}
void seti(int i) {this->i=i;}
int geti(){return i;}
private:
int i;
};

void f1(A t1)         {printf(“hi”);}//copy of obj t=t1

int main()
{
A t;
t.seti(2);
printf(“%d”,t.geti());
f1(t);
return 0;
}

Output:
1 2 hi

 
Destructors
1. destructors are functions which can be used to to deallocate memory for non static variables in case they have been allocated memory dynamically.
2. they get called automatically when the object goes out of memory.
when object goes out of memory (depends.)
if the object is on non heap area, then on storage class.
Dif object is on heap then we need to use some explicit operator.
Destructor is only one per class it cannot be overloaded.
destructor is a death wish for the object.
object is about to die.
system asks tell me what I can do for you
object should tell please call destructor.
and then object should die, it cannot tell after the destructor is getting called, I want to be alive now.
new and delete are operators which are used in C++ to allocate and deallocate dynamic memory.
in C, the statement should be malloc and free are functions which are used in C to allocate and deallocate dynamic memory.
new and delete are guranteed to call the constructor and destructor respectively free and malloc can never call destructor or constructor.

User-defined copy constructor
class A
{               //program proves that with system given copy constructor
// we get entertainment.
public:
A(A &z){ x = (int*) malloc(sizeof(int)); *x = z.getx(); }
~A() { free(x); printf("destructor of A is getting called");}
A() { printf("1"); x = (int*)malloc(sizeof(int)); }
void setx(int y) {   *x = y; }
int getx() { return *x; }
private:
int *x;
};

int main()
{               A obj;
obj.setx(3);
A obj2 = obj; //obj2 should be created based on obj ie cc  at work.
printf(“%d peaceful so far”,obj2.getx());
}

Anonymous object

Class A
{
Public:
A(){A(3); i=0;}
A(int k) {i=k;}
int geti(){return I;}
private:
int i
};

Int main()
{
A obj;
Printf(“%d”,obj.geti(1)};
}

Output=0

Operator overloading
–it is a technique through which we can teach an existing operator, how to deal with user-defined objects.
1. we cannot create new operators in C++ by using operator overloading.
2. we cannot change existing behaviour of operators.
3. during operator overloading we cannot change the number of operands an operator takes  or precedence of an operator.
4. some operators cannot be overloaded.
5. some operators have to written as a function of the class.
6. other operators can be implemented as a member function of a class or as global function.

Ex:
class Device
{
public:
int getDeviceId() { return deviceId; }
Device() { printf("\n"); }
Device(int x ,int y) { deviceId =x; status = y; }
int compareTwoDevices(const Device &d)
{
printf("hello know basics");
return 1;
}

int operator==(const Device &d)
{
printf(“believe the function is getting called”);
if( deviceId == d.deviceId)
return 1;
else
return 0;
}

private:
int deviceId;
int status;
};

int main()
{
Device d1(2,3);
Device d2(2,3);
if(d1==d2)
printf(“they are equal”);
else
printf(“they are not equal”);
}

Output:
Function is getting called
They are equal.

Const function
–function has to be a non-static function of the class
–once function is made constant, it cannot change the state(non-static variables associated) of the object.
— const function can call other const functions only.
Used where?
–dealing with non-static variables.
–inside the class
–for functions
–can call other const function only.
Ex:
Int geti() const{return I;}//assuming I is non-static
Const objects
–object whose state cannot be changed
–can call only const function
—must be set only in constructors.

Ex:
Main()
{
Const A obj;
}
Mutable
–it is a storage class(1 out of 5 in c++)
–can be associated with only non-static variables of class.
–Once a variable is made mutable, only const function can change the variable.

Exception handling
1. it is a mechanism to handle runtime errors.
2. advantage of exception handling is that we can separate normal flow of code from error rectification flow.
Ex:
intialize modem
if(modem initlaized)
connect modem
if(modem connected)
send data
else
modem not connected
else
modem not itnialilzed.

//this is error handling, not exception handling

try
{
intializemodeml
connect modem
send data
close modem
}catch(modem not initialized)

{               }
catch(modem not connected)
{}
catch(data not send)
{               }

Good example:
int main()
{
cout << "Start\n";
try { // start a try block
cout << "Inside try block\n";
throw 100; // throw an error
cout << "This will not execute";
}
catch (int i) { // catch an error
cout << "Caught an exception -- value is: ";
cout << i << "\n";
}
cout << "End";
return 0;
}

Exception spawning
f1 calls f2
exception occurs in f2, it is not handled there, then control comes to f1, if it is handled there, then control shifts to catch block of f1 and flow continues.

 
Set_terminate()
–input arguments for set_terminate is another function.
–it is an example of function pointer
Ex:
F1(){pf(“”);}
Set_terminate(f1);

Templates
–template is a data type independent way of writing code.
Ex:
template <class abcv> //here class is a syntax to indicate some data type, it could be any data type

void f1(abcv y)
{
cout <<"\n"<<  y;
}

int main()
{
f1(‘a’);
f1(“hello”);
f1(5);      }

Template function(generic function)
A function whose input argument is independent of data type, it could be 1 or it could be many does not matter, at least 1 should be there.

Template class(generic class)
a class whose non static variable is independent of data type.
–templates is a compile time concept.
–compiler makes copies of template classes or functions depending on how many types the function or class is associated.

Template specialization
As in above example, During call we pass any data type and it takes but if we crete function for special type,it gets called(this is specialization).

Inheritance
–hierarchy is important
–extensibility
–substitutability
–reusability
–Base class/derived class or super class/sub class

Extensibility
–it is a feature where we add some feature in base class and no changes in derived class but still derived class object will be able to access feature added in the base class.

Ex: base class(account) and derived class(savings account).
Substitutability
–base class pointer=base class object or derived class object.
–“=” means “can be substituted with”

 
Overriding
–taking a function of base class and hiding it from derived class object.
–hiding why? Derived class object may not require that function or may need different functionality.
–good base class should be a  combination of both “virtual” and non-virtual functions
–virtual functions allow overriding and something not virtual in base class cannot be made virtual in derived class.
Ex:
Class base
{
Public:
virtual void accept() { cout << "accpet accn and pn number ";}
};

Class derived: public base
{
void accept() {  cout << “do accept of Account \
and also accept number of withdrawls”; }
}

Int main()
{
C=new base;//or c= new derived
c->accept();
}                                                                               Poc: inher.cpp

Run-time Polymorphism
Run-time polymorphism= substutabilty+overriding
–a particular function is getting called but compiler donot know, it can be base class or derived class, it will come to know at run-time because only at run-time object will be created
(This is run-time Polymorphism).

Ex:
class base {
public:
virtual void vfunc() {
cout << "This is base's vfunc().\n";
}
};

class derived1 : public base {
public:
void vfunc() {
cout << “This is derived1’s vfunc().\n”;
}
};

class derived2 : public base {
public:
void vfunc() {
cout << “This is derived2’s vfunc().\n”;
}
};

int main()
{
base *p, b;
derived1 d1;
derived2 d2;
// point to base
p = &b;
p->vfunc(); // access base’s vfunc()
// point to derived1
p = &d1;
p->vfunc(); // access derived1’s vfunc()
// point to derived2
p = &d2;
p->vfunc(); // access derived2’s vfunc()
return 0;
}

Abstract class 
1. class designed for inheritance.
there must be a derived class for the abstract class
2. The abstract class imposes some conditions on the derived class.
Syntax:
Simple class with pure virtual class
Virtual int geti()=0;

 
Interface
Interfaces. == abstraction ( loose coupling) == standarization == contract== future proof
–interface will have onlypure virtual functions in them and interface will not have any variables and it is public.

Run-time type identification
–done only when there is RTP.
–base class pointer does not have ability to access exclusive function of derived class.
–we want to access exclusive function of derived class, so, we have to typecast base class pointer to a derived class pointer.
Here, new object ofderived class is not created and during typecasting we need to find what type of object we are pointing to.
Ex:
class person
{
public:
person()
{
printf("\nperson cons");
}

virtual void get(){ printf(“\nperson”);}
virtual void job()
{
printf(“\nhell”);
}

virtual ~person()
{
printf(“\nbye bye person”);
}
};

class doctor:public person
{
public:
doctor()
{
printf(“\ndoctor cons”);
}

void display()
{               printf(“doing surgery”);
}

void job()
{
printf(“\npure”);
}

~doctor()
{
printf(“\nbye bye docv”);
}
};

class bussinessman: public person
{
public:
bussinessman()
{
printf(“\nbussinessman cons”);
}

void print()
{               printf(“\nbussiness”);
}

void job()
{
printf(“\nselling”);
}

virtual ~bussinessman()
{
printf(“\nbye bye bussiness”);
}
};

person* getSomeperson()
{
person *p =NULL;
int choice =0;
cout << “\n 1. Person \n 2. Doctor \n 3. bussinessman”;
cin >> choice;
if( 1 == choice)
p =new person;
else if( 2 == choice)
p =new doctor;
else if( 3 == choice)
p =new bussinessman;
return p;
}

int main()
{
person *ptr=getSomeperson();
ptr->job();
doctor *z = dynamic_cast<doctor *>(ptr);
if(z!=NULL)

{                 z->display();                }

else          printf(“\nnot a doctor “);

bussinessman *y=dynamic_cast<bussinessman *>(ptr);

if(y!=NULL)

{          y->print();                }
else     printf(“\nnot a bussiness “);
delete ptr;
}
 

This entry was posted in Material and tagged , , , , , , , , , , , , , . Bookmark the permalink.

Leave a comment