[quote]What is C++?[/quote]
C++ is C with classes. It was designed to manage large amounts of code, and so that a line of C++ expresses more thing than a line of C. The main functionalities C++ adds to C are:
- Control of the accessibility to code within the source files (namespace, struct, and class).
- Mechanisms that make a line of code more expressive (constructors, destructors, operators, …).
- Object programming (class derivation).
- Generic programming (templates).
[quote]How to use namespaces in C++?[/quote]
A namespace allows to code different entities without bothering about unicity of names. A namespace is a logical entity of code. A namespace can be included in another namespace. If a namespace is anonymous, its code is only accessible from the compilation unit (.cpp file), thus equivalent to using static and extern in C.
// in test1.cpp namespace name1 { void function1() { /* ... */ } namespace name2 { void function2() { /* ... */} } } namespace // anonymous namespace { void function() { /* ... */ } } void function3() { function(); } // in test2.cpp void function4a() { function1(); } void function4c() { name1::function2(); } void function4c() { function(); } void function4b() { name1::function1(); } void function4d() { name1::name2::function2(); } using namespace name1; //makes accessible the entire namespace name1 void function4e() { function1(); } // ok void function4f() { name2::function1(); } // ok using name1::name2::function2; //makes accessible function2 only void function3g() { function2(); } // ok
[quote]How do I use references in c++?[/quote]
A reference is merely an initialized pointer. This reduces significantly zero pointer and un-initialized pointers errors. Prefer references to pointers. Although the two following codes look equivalent, the second implementation prevents invalid compilation.
// in C int i; int *ptr = &i; int *temp; *ptr = 0; *temp = 0; // segfault |
// in C++ int i; int &ref = i; int &tempRef; // g++ refuses to compile that ref = 0; tempRef = 0; |
[quote]How do I declare, assign and call a pointer to a function in c++?[/quote]
int fun(int, char) { // ... } // ... int (*ptrFun)(int, char); // pointer to a function ptrFun = fun; // assignment ptrFun = &fun; // alternative int r = (*ptrFun)(42, 'a'); //calling
[quote]How do I declare a type of a pointer to a function?[/quote]
int (*ptrFun)(int, char);
[quote]How do I declare an array of pointers to a function?[/quote]
typedef int (*ptrFun)(int, char); ptrFun array[10]; // array of 10 pointers to a function
[quote]How do I use class and struct?[/quote]
A C++ struct is almost like a struct in C (i.e. a set of attributes) but has two additional kinds of members: methods and data types. A class method has to be used with an instance of that class. The important is that methods have always access to their instance’s attributes and data types.
class testA { typedef char t_byte; // type unsigned char i; // attribute void fun() // method { t_byte b = 1; // fun can access type t_byte i = b; // fun can access type i } }; void function() { testA variable; variable.fun(); // an instance is required to call a method. }
[quote]When we have to use a class or a struct?[/quote]
In a struct, the members are public by default. In class, the members are private by default. Since in C++ privacy is a virtue, prefer class to the struct.
[quote]Who can access to class members?[/quote]
There are three levels of access to members
- private: access is granted only to the class’ methods and to friend functions and classes.
- protected: access is granted only to the methods and to derived classes’ methods.
- public: access is granted to everyone.
Restricting access to members is useful for detecting illicit use of the members of a class when compiling, as shown in the following code.
class testA { private: int a; void fun1() {/*...*/} protected: int b; void fun2() { func1(); } public: int c; void fun3() { /*...*/ } }; void function() { testA obj; obj.a = 0; //Error it's private obj.fun1(); //Error obj.b = 0; //Error it's protected obj.dun2(); //Error obj.c = 0; //ok obj.fun3(); //ok }
[quote]What is private, protected or public?[/quote]
These are access specifier in c++. Use them in this order of increasing preference: public, protected, private.
[quote]How to create an instance of a class?[/quote]
In C++ an instance can be created by using the class name. When an instance is created a special kind of method is called i.e contractors. There are four possible ways of specifying constructors
- default constructor
- copy constructor
- parameterized constructor
- conversion constructor
- copy assignment
class testA { testA() { /* ... */ } // default constructor testA(const testA &a) { /* ... */ } // copy constructor testA(int i, int j) { /* ... */ } // parameterized constructor testA &operator=(const testA &a) { /* ... */ } // copy assignment }; class testB { testB() { /* ... */ } // default constructor testB(const testA &a) { /* ... */ } // conversion constructor }; void function() { testA a(0, 0); // shortcut, parameterized constructor testA a1(a); // shortcut, copy constructor testB b(a1); // shortcut, conversion constructor testB b1; // shortcut, default constructor b1 = a1; // conversion constructor a1 = a; // copy assignment }
[quote]How to initialize members of a class?[/quote]
There are two ways.
- default constructor
- parameterized constructor
class testA { private: int a; int b; testA() { a = 0; b = 0; } testA(int a1, int b1) { a = a1; b = b1; } };
[quote]How to initialize a const member?[/quote]
Since the value of a const member cannot be assigned with operator =, its value must be initialized as follows:
class testA { const int id; testA(int i) { id = i; // attribute id is initialized to the value of parameter i } };
c++ interview questions
[quote]How to call a super/parent constructor?[/quote]
class testA { testA() { /* ... */ } }; class testB { testB() { testA() // call to parent’s constructor. } };
[quote]What is a destructor?[/quote]
it’s a special kind of member function which is executed automatically when an object about to destroy. Always destructor starts with ‘~’ symbol followed by class name.
[quote]How we can deallocate memory a class in c++?[/quote]
The method called when the memory occupied by a class is freed is called the destructor. With derived classes, the destructor should always be virtual. If a class is destroyed through a base class pointer whose destructor isn’t virtual, the result is undefined (only part of the destructors will be called).
class testA { testA() {} virtual ~testA() {} }; class testB: public testA { testB() {} ~testB() {} }; void function() { testB *b = new B(); testA *a = b; delete a; // calls ~testA and ~testB. If ~testA wasn’t virtual, only ~testA would be called. }
[quote]How to implement a method outside classes?[/quote]
It is possible to place the prototype of a method in a class and implement code outside. This is recommended because it allows the programmer to read a short prototype of the class, and makes re-usability easier
// in a header file (.h file) class testA { int a; testA(); virtual ~testA(); void fun(); }; // in a compilation unit (.cpp file) testA::testA() { /* ... */ }; testA::~testA() { /* ... */ }; void testA::fun() { /* ... */ };
[quote]How to implement methods outside classes in a header file?[/quote]
The code of a method specified in a header file must be declared inline. It means that when compiling, the calls to the method will all be replaced by the code of that method.
//code in .h file class testA { int a; testA(); }; inline testA::testA() { /* ... */ }
[quote]How to declare, assign and call a pointer to a method?[/quote]
Note that a pointer to a method does not hold a second pointer to an instance of a class. To use a pointer to a method, you need an instance of the class into which this method can be called (possibly a second pointer).
class testA { void func(int) {} }; void function() { void (testA::*pm)(int) = &testA::func; // pointer on method testA obj; // instance of a class (obj.*func)(1); // calling the method with parameter value 1 }
[quote]How to declare a method that returns a pointer to a function?[/quote]
The following method takes parameter a char and returns a pointer to a function. To avoid this heavy syntax, you may use a typedef.
class testA { void (*m(char))(int) { /* ... */ } }; testA a; void (*pf)(int); pf = a.m(’a’);
[quote]How to specify a pointer to a static method?[/quote]
It works exactly like pointers to functions in C.
class testA { static void sum(int) {} }; void function() { void (*psm)(int) = testA::sm; // assignment void (*psm)(int) = &A::sm; // alternative (*psm)(1); // calling the method with parameter value 1. }
[quote]How to access the private part of a class from another class or function?[/quote]
A class can define friends: functions or classes. The friends will have access to the private part of that class. If a function is a friend, it has to be prototyped or defined before specifying its friendship.
class testA { }; void fun(); // fun prototyped before class testB { friend A friend void func(); }; void f() { /* ... */ }
[quote]How to prevent the compiler from doing implicit type conversions?[/quote]
Use the keyword explicit on the constructor. Forcing explicit conversions is useful to make the programmers aware of the conversion. This is especially interesting for time-consuming conversions.
class testA { testA() {} }; struct testB { testB() {} testB(const testA &a) {} }; class testC { testC() {} explicit testC(const testA &a) {} }; void funcB(testB b) { /* ... */ } void funcC(testC c) { /* ... */ } void function() { testA a; testB b; testC c; funcB(a); // ok, conversion is implicit funcC(a); // error funcC(testC(a)); // ok, conversion is explicit }
[quote]When should use const methods?[/quote]
When a method isn’t going to modify a class, it should be const. This prevents from modifying attributes unwantedly, and reduces significantly errors:
class testA { int a; bool fun(int i) const { if (a = i) . // error. fun shouldn’t modify a. return true; else return false; } };
freshers c++ interview questions and answers
[quote]How to modify attributes in a const method?[/quote]
When you have no other choice (which happens), use the keyword mutable:
struct testA { int a; mutable int b; void fun() const { a = 0; // error b = 0; // ok } };
[quote]What are the static members?[/quote]
Static members are members that exist independently from an instantiation of a class. They are shared by all instances of that class and can be used without requiring an instance. Only methods and attributes can be static members1. A static attribute must be defined in a .cpp file.
struct testA { static int id; static int genId() { return id++; } }; testA::id = 0; // defined in .cpp file
[quote]When should use a static method or a function?[/quote]
A static method has full access to the members of a class. If this isn’t required, the method should be a function.
class testA { private: int i; public: static void fun(testA &a) { a.i = 0; } };
[quote]When should use a static method or a friend function?[/quote]
A static method has full access to the members of a single class. A function can be the friend of more than one class, and therefore can have access to the members of one of more classes.
[quote]When should use a global variable or a static attribute?[/quote]
If possible, avoid global variables.
[quote]How to call a static member outside a class?[/quote]
class testA { static int id; static int genId() { return id++; } };
This adds a third meaning to the keyword static: the first is a local definition of a function or variable inside a compilation unit, the second is a variable instantiated only once inside a function or method.
int function() { A::id = 0; // call to a static attribute return A::gendId(); // call to a static method }
[quote]How do you derive classes?[/quote]
The purpose of deriving classes is to factor code: if two classes derive from a parent class, the members defined in the parent will be accessible by both and have to be coded only once. The level of access to a parent’s member is specified with public, private and protected. The following examples show the three types of derivation and their effect.
class A { /* ... */ }; //access to members of A is transmitted to B. class B: public A { /* ... */ }; //public members of A become protected members of C class C: protected A { /* ... */ }; //public and protected members of A become private members of D class D: private A { /* ... */ };
[quote]How to avoid ambiguities with multiple class derivation?[/quote]
Consider the two following valid examples: the left one if non-ambiguous, the right one is.
class testA { void a() {} }; struct B: public virtual A { }; struct C: public virtual A { }; struct D: public B, public C { }; void function() { D d; d.a(); } |
class A { void a() {} }; struct B: public virtual A { }; class C: public A { }; class D: public B, public C // D has two a { }; void function() { D d; d.a(); // error, ambiguous d.B::a(); // ok d.C::a(); // ok } |
[quote]What is a virtual method?[/quote]
A virtual method in a parent allows children to have a different implementation for it. A pure virtual method in a parent forces children to have an implementation for it. A class with a pure virtual method is called virtual.
class testA { virtual void f1() = 0; virtual void f2() { /* ... */ } }; class B: public A { void f1() { /* ... */ } }; class C: public A { void f1() { /* ... */ } void f2() { /* ... */ } };
[quote]What are templates?[/quote]
Template allow the programmers to implement algorithms once for various data types. Contrarily to macros, the compiler checks the syntax. Functions, methods, and classes can be templated. Template parameters are of two kinds: data types or integers.
[quote]How to specify a function template?[/quote]
In a header (.h file) : template <class T> T max(T a, T b) { return (a < b) ? b: a; }
[quote]How to specify a class template?[/quote]
In a header (.h file). The template parameter can be used for defining any member of the class.
template <class T, int N> class Vector { T array[N]; void method(T t, int i) { array[i] = T; } };
[quote]How do I specify a template method?[/quote]
In a header (.h file)
class Vector { int array[3]; template <class TVECTOR2> void eqAdd(TVECTOR2 v2); }; template <class TVECTOR2> void Vector::eqAdd(TVECTOR2 a2) { for (int i(0); i < 3; ++i) array[i] += a2[i]; }
c++ freshers interview questions and answers
[quote]How to place the template method code outside classes?[/quote]
template <class T, int N> class Vector { T array[N]; void reset(); }; template <class T, int N> void Vector<T, N>::reset() { for (int i(0); i < N; ++i) array[i] = 0; }
[quote]How to write a template method of a template class?[/quote]
The syntax is a bit heavy. There is no point of using it unless you really need to.
template <class T, int N> class Vector { T array[N]; template <class F> void apply(F f); }; template <class T, int N> template <class F> void Vector<T, N>::apply (F function) { for (int i(0); i < N; ++i) array[i] = f(array[i]); }
[quote]How to specify a friend template class?[/quote]
Like that:
class A { template<class> friend class B; friend class B <class T>; };
[quote]How to write different code for different template parameters?[/quote]
Use specializations:
template <class T, int N> class Vector { T a[N]; public: Vector(const T v) { for (unsigned i(0); i < N; ++i) a[i] = v; } }; template <> class Vector <double, 3> { double x, y, z; public: Vector(const double v): x(v), y(v), z(v) {} };
[quote]How to write to the standard output in a C++ way?[/quote]
Include iostream and use the operator <<. std::cout << “Hello!” << std::endl;
[quote]How to read from the standard input in a C++ way?[/quote]
Include iostream and use the operator >>. For a string of undefined length, use getline.
float f; char str[255]; std::cin >> f; std::cin.getline(str, 255);
[quote]How to specify a copy constructor for a class whose code is not accessible?[/quote]
Use the keyword operator.
// suppose class A’s code is not accessible A::A(const int i) { /* ... */ } // This does not prevent you to make a B to A convertor class B { int b; B(c onst int i): b(i) {} operator A() { return A(b); } };
[quote]How to redefined arithmetic operators?[/quote]
There are two ways of redefining an operator: with a method or with a function (usually friend function, for most operators need to access the private members of a class). Some operators can only be redefined with a method.
[quote]When should use operator [] or ()?[/quote]
Use () instead of []: calling [] on a pointer to the array (instead of the array) will compile too, but will have a different effect.
[quote]When should I use operator i++ or ++i?[/quote]
Since i++ returns a copy of i, it is preferable to use ++i. 6.37 How do I cast types?
Remember that an explicit type conversion often reveals an error of conception. To cast a variable an into another type T, use one of the following:
static_cast<T>(a) // explicit and standard conversion dynamic_cast<T>(a) // validity of object checked at run-time reinterpret_cast<T>(a) // binary copy const_cast<T>(a) // changes the constness
One Response