Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How class constructor works in C++

Tags:

c++

I saw an online C++ test regarding the constructor. I can figure out most of the answers but am puzzled by some in the following. Hope someone can help me out.

Here's the example.

#include <iostream>

class A {
    public:
            A(int n = 0) : m_n(n) {
                    std::cout << 'd';
            }

            A(const A& a) : m_n(a.m_n) {
                    std::cout << 'c';
            }

    private:
            int m_n;
};

void f(const A &a1, const A &a2 = A())
{
}

int main() {
    A a(2), b;
    const A c(a), &d = c, e = b;
    b = d;
    A *p = new A(c), *q = &a;
    static_cast<void>(q);
    delete p;
    f(3);
    std::cout << std::endl;

    return 0;
}

What I don't really get is why "&d = c" doesn't output anything. Also adding another overloading constructor like A(const A *a) : m_n(a->m_n) { std::cout << 'b'; } doesn't output anything either for *q = &a. So what can I do to make it work?

Many thanks for any advice. I am very curious about this.

like image 792
ToonZ Avatar asked Dec 03 '25 11:12

ToonZ


1 Answers

There's no output for these because d and q are not of type A, i.e. they are not A objects. d is a reference to A and q is a pointer to A. Initialising a reference and initialising or assigning a pointer does not manipulate the referred-to/pointed-to A object at all, hence no output.

To address your question - there is nothing to "make work," it works just as it should.

like image 165
Angew is no longer proud of SO Avatar answered Dec 05 '25 23:12

Angew is no longer proud of SO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!