11 Nov 2014

Advance level questions framed on constructor destructor set one




Q1.
#include <iostream>
class A
{
public:
    explicit A(int n = 0) : m_n(n) { }
public:
    A& operator=(const A& a)
    {
        this->m_n = a.m_n;
        ++m_assignment_calls;
        return *this;
    }

     A(const A& a)
    {
        this->m_n = a.m_n;
        ++m_copycontor_calls;
    }


public:
    static int m_assignment_calls;
    static int m_copycontor_calls;
private:
    int m_n;
};
int A::m_assignment_calls = 0;
int A::m_copycontor_calls = 0;

A f(const A& a) { return a; }
A g(const A a) { return a; }
int main()
{
    A a(3);
    A b = a;
    std::cout << A::m_assignment_calls;
    std::cout << A::m_copycontor_calls<<endl;
    b = g(a);
    g(b);
    std::cout << A::m_assignment_calls;
    std::cout << A::m_copycontor_calls<<endl;

    const A& c = f(b);
    std::cout << A::m_assignment_calls;
    std::cout << A::m_copycontor_calls << std::endl;
    return 0;
}

Output:
01
15
16

No comments:

Post a Comment