C++ Flashcards
C++
What is encapsulation??
Containing and hiding information about an object, such as internal data structures and code.
Encapsulation isolates the internal complexity of an object’s operation from the rest of the application. For example, a client component asking for net revenue from a business object need not know the data’s origin.
C++
What is inheritance?
Inheritance allows one class to reuse the state and behavior of another class.
The derived class inherits the properties and method implementations of the base class and extends it by overriding methods and adding additional properties and methods.
C++
What is Polymorphism??
Ploymorphism allows a client to treat different objects in the same way even if they were created from different classes and exhibit different behaviors.
You can use implementation inheritance to achieve polymorphism in languages such as C++ and Java.
Base class object’s pointer can invoke methods in derived class objects.
You can also achieve polymorphism in C++ by function overloading and operator overloading.
C++
What is constructor or ctor?
Constructor creates an object and initializes it. It also creates vtable for virtual functions. It is different from other methods in a class.
Constructor with no arguments or all the arguments has default values.
C++
What is a destructor?
In object-oriented programming, a destructor (sometimes shortened to dtor) is a method which is automatically invoked when the object is destroyed.
It can happen when its lifetime is bound to scope and the execution leaves the scope, when it is embedded into another object whose lifetime ends, or when it was allocated dynamically and is released explicitly.
Its main purpose is to free the resources (memory alloactions, open files or sockets, database connections, resource locks, etc.) which were acquired by the object along its life cycle and/or deregister from other entities which may keep references to it.
The use of destructors is a necessity to the concept of Resource Acquisition Is Initialization (RAII).
In a language with an automatic garbage collection mechanism, it would be difficult to deterministically ensure the invocation of a destructor, and hence these languages are generally considered unsuitable for RAII. In such languages, unlinking an object from existing resources must be done by an explicit call of an appropriate function (usually called Dispose()). This method is also recommended for freeing resources rather than using finalizers for that.
C++ has the naming convention in which destructors have the same name as the class of which they are associated with, but prefixed with a tilde (~).
The destructor has the same name as the class, but with a tilde (~) in front of it. If the object was created as an automatic variable, its destructor is automatically called when it goes out of scope. If the object was created with a new expression, then its destructor is called when the delete operator is applied to a pointer to the object. Usually that operation occurs within another destructor, typically the destructor of a smart pointer object.
In inheritance hierarchies, the declaration of a virtual destructor in the base class ensures that the destructors of derived classes are invoked properly when an object is deleted through a pointer-to-base-class. Objects that may be deleted in this way need to inherit a virtual destructor.
A destructor should never throw an exception.[2]
C++
What is copy constructor?
Constructor which initializes the it’s object member variables ( by shallow copying) with another object of the same class. If you don’t implement one in your class then compiler implements one for you.
It is a constructore which initializes it’s object member variable with another object of the same class. If you don’t implement a copy constructor in your class, the compiler automatically does it.
for example: Boo Obj1(10); // calling Boo constructor
Boo Obj2(Obj1); // calling boo copy constructor Boo Obj2 = Obj1;// calling boo copy constructor
C++
When are copy constructors called?
Copy constructors are called in following cases:
- When a function returns an object of that class by value
- When the object of that class is passed by value as an argument to a function
- When you construct an object based on another object of the same class
- When compiler generates a temporary object
C++
What is assignment operator?
Default assignment operator handles assigning one object to another of the same class.
Member to member copy (shallow copy)
C++
What are all the implicit member functions of the class? Or what are all the functions which compiler implements for us if we don’t define one.??
- Default ctor
- Copy ctor
- Assignment operator
- Default destructor
- Address operator
C++
What is conversion constructor?
Constructor with a single argument makes that constructor as conversion ctor and it can be used for type conversion.
for example:
class Boo { public: Boo( int i ); };
Boo BooObject = 10 ; // assigning int 10 Boo object
C++
What is conversion operator??
Class can have a public method for specific data type conversions.
for example:
class Boo { double value; public: Boo(int i ) operator double() { return value; } };
Boo BooObject;
double i = BooObject; // assigning object to variable i of type double. now conversion operator gets called to assign the value.
C++
What is diff between malloc()/free() and new/delete?
Malloc allocates memory for object in heap but doesn’t invoke object’s constructor to initiallize the object.
New allocates memory and also invokes constructor to initialize the object.
Malloc() and Free()
1. Do not support object semantics
2. Does not construct and destruct objects
string * ptr = (string *)(malloc (sizeof(string)))
3. Are not safe
4. Does not calculate the size of the objects that it construct
- Returns a pointer to void
int *p = (int *) (malloc(sizeof(int)));
int *p = new int; - Are not extensible
new and delete can be overloaded in a class
“delete” first calls the object’s termination routine (i.e. its destructor) and then releases the space the object occupied on the heap memory. If an array of objects was created using new, then delete must be told that it is dealing with an array by preceding the name with an empty []:-
Int_t *my_ints = new Int_t[10];
…
delete []my_ints;
C++
what is the diff between “new” and “operator new” ?
“operator new” works like malloc.
C++
What is difference between template and macro??
define min(i, j) (i < j ? i : j)
There is no way for the compiler to verify that the macro parameters are of compatible types. The macro is expanded without any special type checking.
If macro parameter has a postincremented variable ( like c++ ), the increment is performed two times.
Because macros are expanded by the preprocessor, compiler error messages will refer to the expanded macro, rather than the macro definition itself. Also, the macro will show up in expanded form during debugging.
for example:
Macro:
template: template T min (T i, T j) { return i < j ? i : j; }
C++
What are C++ storage classes?
Auto
Register
Static
Extern
Auto: the default. Variables are automatically created and initialized when they are defined and are destroyed at the end of the block containing their definition. They are not visible outside that block
Register: a type of auto variable. a suggestion to the compiler to use a CPU register for performance
Static: a variable that is known only in the function that contains its definition but is never destroyed and retains its value between calls to that function. It exists from the time the program begins execution
Extern: a static variable whose definition and placement is determined when all object and library modules are combined (linked) to form the executable code file. It can be visible outside the file where it is defined.
What are storage qualifiers in C++ ?
They are..
Const
Volatile
Mutable
Const keyword indicates that memory once initialized, should not be altered by a program.
Volatile keyword indicates that the value in the memory location can be altered even though nothing in the program
code modifies the contents. for example if you have a pointer to hardware location that contains the time, where hardware changes the value of this pointer variable and not the program. The intent of this keyword to improve the optimization ability of the compiler.
Mutable keyword indicates that particular member of a structure or class can be altered even if a particular structure variable, class, or class member function is constant.
struct data { char name[80]; mutable double salary; }
const data MyStruct = { “Satish Shetty”, 1000 }; //initlized by complier
strcpy ( MyStruct.name, “Shilpa Shetty”); // compiler error
MyStruct.salaray = 2000 ; // complier is happy allowed
C++
What is reference?
Reference is a name that acts as an alias, or alternative name, for a previously defined variable or an object.
prepending variable with “&” symbol makes it as reference.
for example:
int a;
int &b = a;
C++
What is passing by reference?
Method of passing arguments to a function which takes parameter of type reference.
for example:
void swap( int & x, int & y ) { int temp = x; x = y; y = temp; }
int a=2, b=3;
swap( a, b );
Basically, inside the function there won’t be any copy of the arguments “x” and “y” instead they refer to original variables a and b. so no extra memory needed to pass arguments and it is more efficient.
C++
When do use “const” reference arguments in function?
- Using const protects you against programming errors that inadvertently alter data.
- Using const allows function to process both const and non-const actual arguments, while a function without const in the prototype can only accept non constant arguments.
- Using a const reference allows the function to generate and use a temporary variable appropriately.
C++
When are temporary variables created by C++ compiler?
Provided that function parameter is a “const reference”, compiler generates temporary variable in following 2 ways.
- The actual argument is the correct type, but it isn’t Lvalue
double Cube(const double & num) { num = num * num * num; return num;
}
double temp = 2.0;
double value = cube(3.0 + temp); // argument is a expression and not a Lvalue;
- The actual argument is of the wrong type, but of a type that can be converted to the correct type
long temp = 3L;
double value = cuberoot ( temp); // long to double conversion
C++
What is virtual function?
When derived class overrides the base class method by redefining the same function, then if client wants to access redefined the method from derived class through a pointer from base class object, then you must define this function in base class as virtual function.
class parent { void Show() { cout << "i'm parent" << endl; } };
class child: public parent { void Show() { cout << "i'm child" << endl; } };
parent * parent_object_ptr = new child;
parent_object_ptr->show() // calls parent->show() i
now we goto virtual world…
class parent { virtual void Show() { cout << "i'm parent" << endl; } };
class child: public parent { void Show() { cout << "i'm child" << endl; } };
parent * parent_object_ptr = new child;
parent_object_ptr->show() // calls child->show()
C++
What is pure virtual function? or what is abstract class?
When you define only function prototype in a base class without implementation and do the complete implementation in derived class. This base class is called abstract class and client won’t able to instantiate an object using this base class.
You can make a pure virtual function or abstract class this way..
class Boo { void foo() = 0; }
Boo MyBoo; // compilation error
C++
What is Memory alignment??
The term alignment primarily means the tendency of an address pointer value to be a multiple of some power of two. So a pointer with two byte alignment has a zero in the least significant bit. And a pointer with four byte alignment has a zero in both the two least significant bits. And so on. More alignment means a longer sequence of zero bits in the lowest bits of a pointer.
C++
What problem does the namespace feature solve?
Multiple providers of libraries might use common global identifiers causing a name collision when an application tries to link with two or more such libraries. The namespace feature surrounds a library’s external declarations with a unique namespace that eliminates the potential for those collisions.
namespace [identifier] { namespace-body }
A namespace declaration identifies and assigns a name to a declarative region.
The identifier in a namespace declaration must be unique in the declarative region in which it is used. The identifier is the name of the namespace and is used to reference its members.