mercredi 29 juin 2016

Initialize a const class member with a default value


I have two classes A and B. bclass of type B is a constant member of class A; what I want to do is to initialize class bclass with default values if no B object is provided to A. Something like this:

#include <iostream>
#include <string>
#include <unistd.h>

using namespace std;

class B{
public:
  B(string Bs): Bstring(Bs){
    cout << "B constructor: " << Bstring << endl;
  }

  ~B(){
    cout << "B destructor: " << Bstring << endl;
  }

private:
  const string Bstring;
};

class A{
public:
  A(const B subb = B("mmmmm")): bclass(subb){
    cout << "A constructor." << endl;
  }

  ~A(){
    cout << "A destructor." << endl;
  }

private:
  const B bclass;
};

int main(void){
    A a;
    cout << "doing work..." << endl;
    sleep(2);
    return 0;
}

The output is:

B constructor: mmmmm
A constructor.
B destructor: mmmmm
doing work...
A destructor.
B destructor: mmmmm

The thing is that I'm constructing 2 B classes(?) when only one is needed! And somehow, B constructor is called only once, while the destructor is called twice... What is going on?!


Aucun commentaire:

Enregistrer un commentaire