šŸ“œ ā¬†ļø ā¬‡ļø

Top C ++ Interview Questions and Answers

Hello!

Those who are engaged in programming sooner or later face the need to undergo a technical interview with a potential employer.

The fact that C ++ programmers are asked during the interview, as well as the answers to these questions will be discussed in this post.

Foreword


A small introductory part in the form of question-answer, to clarify some points and try to answer possible questions on this post.
')
Why all this?
I want to collect real questions and answers to them in one post. Because I’m not satisfied with the ones that I see on the Internet, they are sometimes too blurred (for example, 75 pages per game-devil), or just a few examples, or with errors that no one can fix, or with links to already dead topics, or what something far-fetched, ... the list goes on.

In general, I want to have a list with the most popular questions on this topic, and if, suddenly, you need to refresh your knowledge so that you do not have to go into any notes, run IDE or google, and you can open one place and read everything there.

This topic should seem most interesting to those who are just beginning their steps in this boundless sea called C ++ .

Where will the questions come from?
From my little experience, the experience of people I know, and also, I hope that you will offer many interesting things from your own experience or the experience of your acquaintances.

What will be the structure of these questions?
Linear list. Questions will be added as they are received, I will try not to drop this section and update it. At the end I will put the last update date, so that it was clear when the list was last changed.

Now I plan to write the first 20 questions, and if this topic is in demand, I will gradually add new ones.

You have a mistake in the code, how did you overlook it?
It is human nature to make mistakes and I do not consider myself a guru who can write without error. And this is C ++, here the probability of making a mistake is even greater.

If you see an error, write about it, and I will fix it.

Q & A


1. Why do I need a virtual destructor?

Answer: To avoid possible resource leaks or other uncontrolled behavior of the object, the logic of which includes the call to the destructor.
Example:
class Base
{
public:
    virtual ~Base()
    {
        std::cout << "Hello from ~Base()" << std::endl;
    }
};

class Derived : public Base
{
public:
    virtual ~Derived()
    {
        //      
        std::cout << "Hello from ~Derived()" << std::endl;
    }
};

Base *obj = new Derived();
delete obj;

Output:
Hello from ~Derived()
Hello from ~Base()


virtual Base . .. ~Base():

Output:
Hello from ~Base()

GooRoo . .

2. ?

: , c , , , , .
:
class Base
{
private: 
    HANDLE m_hFile;

public:
    Base()
    {
        std::cout << "Hello from Base()" << std::endl;
        m_hFile = ::CreateFileA(...);
        //  ,       
        SomeLib.SomeFunc(...);
    }

    virtual ~Base()
    {
        std::cout << "Hello from ~Base()" << std::endl;
        //     
        ::CloseHandle(m_hFile);
    }
};

try
{
    Base b;
}
catch(const std::exception &e)
{
    std::cout << "Exception message: " << e.what() << std::endl;
}

Output:
Hello from Base()
Exception message: Something failed


, . m_hFile ( ) .. CloseHandle() . .. : - .

: Ā« Ā». : Ā« Ā». :
class Base
{
private: 
    class CHandle
    {
    public:
        ~CHandle()
        {
            ::CloseHandle(m_handle);
        }
    private:
        HANDLE m_handle;
    public:
        //   smart pointer'   
        //  ,        
        void operator = (const HANDLE &handle)
        {
            m_handle = handle;
        }
    };

    CHandle m_hFile;

public:
    Base()
    {
        std::cout << "Hello from Base()" << std::endl;
        m_hFile = ::CreateFileA(...);
        //  ,       
        SomeLib.SomeFunc(...);
    }

    virtual ~Base()
    {
        std::cout << "Hello from ~Base()" << std::endl;
    }
...

Base , .. Base m_hFile CHandle, .

, , , , . boost, Loki, ATL .., .

3. const?

:
  1. , , ..
1. :
const int i = 1;
i = 2; // error C3892: 'i' : you cannot assign to a variable that is const

2. :
int i = 1;
int* const j(&i);
int k = 2;
*j = k; // Ok
j = &k; // error C3892: 'j' : you cannot assign to a variable that is const


3. :
class Foo
{
private:
    int i;
public:
    void func() const
    {
        i = 1; // error C3490: 'i' cannot be modified because it is being accessed through a const object
    }
};

: , mutable. mutable CPP .

4. - ?

: , , :
template <typename T >
void bubble_sort( T &a )
{
    for( T::size_type i = 0; a.size() && i < a.size() - 1; ++i )
    {
        for( T::size_type j = i; j + 1 > 0; --j )
        {
            if( a[j] > a[j+1] )
                std::swap( a[j], a[j+1] );
        }
    }
}

std::vector<int> v;
v.push_back( 7 );
v.push_back( 1000 );
v.push_back( 134 );
v.push_back( 23 );
v.push_back( 1 );
bubble_sort( v );

5. ?

: , , :
template <typename T >
void invert_string( T &a )
{
    T::size_type length = a.size();
    for( T::size_type i = 0; i < (length/2); ++i )
    {
        std::swap( a[i], a[length - i - 1] );
    }
}

std::string str = "abcdefg";
invert_string(str);

6. ?

: private =.
:
class NonCopyable
{
public:
    NonCopyable(){}

private:
    NonCopyable(NonCopyable&){}
    
private:
    void operator=(const NonCopyable&){}
};

NonCopyable a; 
NonCopyable b = a; // error C2248: 'NonCopyable::NonCopyable' : cannot access private member
a = b; // error C2248: 'NonCopyable::operator =' : cannot access private member

7. struct class?

: . struct public, class private. , struct — public, class — private.
:
struct Foo
{
    int i;
};
class Bar
{
    int i;
};

Foo a;
a.i = 1; // Ok
Bar b;
b.i = 1; // error C2248: 'Bar::i' : cannot access private member declared in class 'Bar'

8. , ?

: .. , <, .
:
struct Foo
{
    int i;
};
inline bool operator < (const Foo & lhs, const Foo & rhs)
{
    return lhs.i < rhs.i;
}

std::set<Foo> data;
Foo a, b, c;
a.i = 7;
b.i = 1;
c.i = 6;
data.insert( a );
data.insert( b );
data.insert( c );
//   data     1 6 7

operator < Foo set, .. set'.

STL . , STL , , .

, (Comparison class), , .

9. ?

: sizeof + ( 4 ) + sizeof vtable ( ) + , ( * )
:
struct Foo
{
    int i;
    char a;
};

int size = sizeof(Foo); // 8 ,  int + char = 5.       4, ..       4 .

//    1 
#pragma pack(push, 1)
struct Foo
{
    int i;
    char a;
};
#pragma pack(pop)

int size = sizeof(Foo); // 5 

10. pure virtual function call ?

: .. , . .. , .
:
class Base
{
public:
    Base()
    {
        base_func();
    }
    void base_func()
    {
        func(); // pure virtual function call exception
    }
    virtual void func() = 0;
};
class Derived : public Base
{
public:
    virtual void func()
    {
    }
};

11. vector deque?

: deque push_front pop_front. , vector -, .. , deque . vector , deque / (O(1) O(n)), , .

12. ?

: .
:
class Base
{
public:
    int i;
};
class Derived : private Base
{
    // i     private
};
class Derived2 : private Derived
{
public:
    Derived2()
    {
        i = 2; // error C2247: 'Base::i' not accessible because 'Derived' uses 'private' to inherit from 'Base'
    }
};

Derived d;
d.i; // error C2247

private protected public private. protected public protected. public . .

13. ?

(Wiki): — , e ( ). () .

. : public.

. : private, protected.

14. ?

(Wiki): .
:
class Figure 
{
    ...
    void Draw() const;
    ...
};
 
class Square : public Figure 
{
    ...
    void Draw() const;
    ...
};
 
class Circle : public Figure 
{
    ...
    void Draw() const;
    ...
};


.. , , Draw().

15. malloc new?

: malloc — , (non-typesafe), .. void * . new — , (typesafe), .. .

16. ?

: — , . — . , .. .
:
//  
class Foo
{
public:
    //   
    virtual void func() = 0;
};
class Bar : public Foo
{
public:
    virtual void func()
    {
    }
};

Foo f; // error C2259: 'Foo' : cannot instantiate abstract class	
Bar b; // Ok

17. throw ?

: .
:
try
{
    //....
    try
    {
        // Call something
    }
    catch(const std::exception& )
    {
        // Make/Check something..
        throw; //    
    }
    //...
}
catch(const std::exception& e)
{
    std::cout << e.what() << std::endl;
}


18. delete delete[]?

: delete , new(). delete[] new[]().
:
class Foo
{
};

Foo *pFoo = new Foo();
delete pFoo;
Foo *pFooArray = new Foo[10]();
delete[] pFoo;

delete (, delete delete[]) : undefined behavior.

19. auto_ptr?

: , . STL .
:
std::auto_ptr<Foo> a(new Foo);
std::auto_ptr<Foo> b;
b = a; // a     Foo

std::vector<std::auto_ptr<Foo>> v;
v.push_back(b); // error C2558: class 'std::auto_ptr<_Ty>' : no copy constructor available or copy constructor is declared 'explicit'

, auto_ptr delete, new[](). - boost , , , shared_ptr shared_array.

20. volatile?

: , , . , .
:
volatile int i = 1; //    ,     .

.. volatile - , , , , volatile .
:
while (1) 
{
    if(i == 1)
    {
        // -    i
    }
}

//   volatile ,        - :
if(i == 1) //    i  ,    ,    
{
    while (1) 
    {
        // -    i
    }
}


24.04 13.35

Source: https://habr.com/ru/post/117996/


All Articles