Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegating to a default C++ constructor

Tags:

c++

Assume a C++ class A with members that can all be copied by the their respective copy constructors. We can rely on the default copy constructor for A to copy its members:

class A {
  private:
    A(const A&) = default; // We don't really need this line
    int a;
    B b;
    double c;
}

But now let's assume that I want to "extend" (or annotate) the default constructor of A so that in addition to copying its members, it does something else, e.g. writes a line to a log file.

I.e. I'd like to write something like:

class A {
  public:
    A(const A& a) : A::default(A) {
      print("Constructing A\n");
    }
  private:
    // like before
}

Unfortunately that is not correct C++ syntax.

So is there a syntax which allows delegating to a default C++ constructor while explicitly defining the same constructor?

like image 961
Dov Grobgeld Avatar asked Jul 19 '26 17:07

Dov Grobgeld


2 Answers

The simplest is to move all members into a base class and write the message in a derived class:

class A_helper {
  private:
    int a;
    B b;
    double c;
};
class A : public A_helper {
public:
   A() = default;
   A(const A& a) : A_helper(a) {
       print("Constructing A\n");
   }
   A(A&& a) : A_helper(std::move(a)) {
       print("Constructing A\n");
   }
};
like image 134
j6t Avatar answered Jul 22 '26 12:07

j6t


You can delegate to the default constructor like you would default-initialize a member variable:

A(const A&) : A()
{
    ...
}
like image 38
Some programmer dude Avatar answered Jul 22 '26 12:07

Some programmer dude



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!