How to invoke parameterised constructor in PIMPL design pattern? - c++

How to use PIMPL design for parameterized constructor?
/* ProcessImpl.h */
class ProcessImpl {
public :ProcessImpl();
ProcessImpl(ProcessID thirdParty_pid);
~ProcessImpl();
}
/* Process.h */
class Process {
public:virtual ~Process () {};
Process();
Process(ProcessID thirdParty_pid);
protected:
void createImpl();
private:
ProcessImpl * _impl;
}
/* Process.cpp */
Process::Process():_impl(NULL) {
}
Process::Process(ProcessID thirdParty_pid) {
createImpl();
_impl->ProcessImpl(ldframework::ProcessID thirdParty_pid);
}
void Process::createImpl(){
if(this->_impl == NULL) {
this->_impl = new ProcessImpl();
}
}
When I compile this I am getting error:
Process.cpp: error: invalid use of class ProcessImpl
This is the line throwing error _impl->ProcessImpl(ldframework::ProcessID thirdParty_pid)
Please help

Since your code is not valid C++ I won't jump into conclusions about your actual implementation, so I will start from the beginning:
If a class has a parametrized constructor, the parameters are needed to directly or indirectly initialize class members and base classes. Since a pimpl'd class has no data members of its own (except the pimpl), constructor parameters are needed only for the initialization of the implementation class.
There are two extremes of the pimpl idiom implementation:
All the logic goes into the implementation class, and the outer class is only a dumb fassade, forwarding any calls to the pimpl.
The logic remains in the outer class, the pimpl is only a dumb bundle of data.
Of course, in practice, anything in between is possible.
In case 1, the outer class' constructor signatures should be the same as the signature of the implementation class' constructors and just pass any arguments to the pimpl constructors:
Foo.h
class Foo {
struct FooImpl;
std::unique_ptr<FooImpl> pImpl;
public:
~Foo();
Foo(A const& a);
Foo(B b, C* c, D& d);
};
Foo.cpp
struct Foo::FooImpl {
FooImpl(A const& a);
FooImpl(B b, C* c, D& d);
/* Logic goes here */
};
Foo::~Foo() {} //defined here for correct deletion of the unique_ptr
Foo::Foo(A const& a)
: pImpl(std::make_unique<FooImpl>(a))
{}
Foo::Foo(B b, C* c, D& d)
: pImpl(std::make_unique<FooImpl>(std::move(b), c, d))
{}
Together:
Use the same constructor signatures for the class and the pimpl-class, each class constructor just calls the corresponding pimpl-constructor
Parameters taken by reference or pointer are passed as-is to the pimpl constructor
Parameters taken by value are moved to the pimpl constructor (forwarding)
That is the simplest possible solutution where the constuctor logic is entirely implemented inside the implementation class.
In the other case, where the pimpl class is only a bundle of data, you will have the logic inside the outer class` constructor, like this:
struct Foo::FooImpl {
FooImpl(A const& a, B b, E e, F f);
A a;
};
Foo::Foo(B b, C* c, D& d)
: pImpl(std::make_unique<FooImpl>(A(), std::move(b), calcE(c,d), getSomeF())
{
pImpl->a = someValueForA();
}
You see, the strategy to implement the constructors depends on your strategy to implement the pimpl idiom alltogether. Just make sure you are somewhat consistent in either delegating the logic to the pimpl class or leaving it in the main class.

Just construct the pimpl in the constructor.
Note that you should also implement a copy constructor and assignment operator as copying the object will result in undefined behaviour when both copies are destructed.
Ideally the pimpl should always be valid to avoid checking if it is valid all the time, but going by your code, you could perhaps have the following:
class Process {
public:
virtual ~Process () {
};
Process() {
// Ideally the impl_ pointer should be intialized to avoid
// having to check it in every function that uses it..
}
Process(ProcessID pid) {
impl_.reset(new ProcessImpl(pid));
}
Process(Process const& rhs) {
if (rhs.impl_.get()) {
impl_.reset(new ProcessImpl(*rhs.impl_));
}
}
Process& operator=(Process const& rhs) {
if (this != &rhs) {
if (rhs.impl_.get()) {
impl_.reset(new ProcessImpl(*rhs.impl_));
}
else {
impl_.reset();
}
}
return *this;
}
private:
std::unique_ptr<ProcessImpl> impl_;
};

Related

How to enforce that construction is always through a certain method?

I have some third-party abstract base class
struct foo
{
virtual foo*job() = 0;
...
static void* make_space(size_t sizeofDerived);
};
which I cannot alter. Objects of type foo (and all derived classes) must only be created/constructed using placement-new into the memory returned by foo::make_space(),
because ordinary construction, as in
derived_from_foo z; // or
auto p = new derived_from_foo();
may cause undesired problems (corrupting memory, depending on the compiler, as I found out eventually). So my question: how can I write/design a derived class
struct bar // still abstract, since foo::job() is not provided
: foo
{
...
template<typename Derived, typename...Args>
static Derived* create(Args&&...args)
{
return ::new(foo::make_space(sizeof(Derived)))
Derived(std::forward<Args>(args)...);
}
};
such that construction of objects of type bar or any type derived from bar by any other means than through bar::create() fails at (i) compilation or (ii, less ideal) at run-time?
You can in fact enforce it, at a price.
Consider this class:
class A
{
public:
class Tag
{
public:
Tag(const Tag&) = default;
Tag(Tag&&) = default;
private:
Tag() {}
friend class A;
};
A(Tag, int a, char b) : a(a), b(b) {}
int a;
char b;
template<typename T, typename ... Params>
static T* make(Params&& ... params)
{
return new T(Tag(), std::forward<Params>(params)...);
}
};
Its constructor requires a Tag parameter, but you cannot make a Tag, it's got a private constructor. You can derive from A, but you cannot directly create objects of a derived class either: it needs to pass a Tag to its parent constructor, and you cannot make one.
So the only way to create an object of A or a derived class is by calling A::make.
Well there is still a way to cheat
class B : public A
{
public:
B(Tag t, double q) : A(t, 42, 'z'), q(q) {
// cheating:
B* other = new B(t, 3.14);
}
double q;
};
If this bothers you, you still can enforce correctness at run-time by making Tag non-reusable à la std::unique_ptr. Remove the copy ctor, throw in a private bool flag that you set on construction and clear on move-out, and check it inside make.

Concrete class not being constructed

I have a class hierarchy like this:
class Base {
public:
virtual bool foo() const = 0;
static Base& getHeadInstance();
};
class Concrete: public Base {
public:
explicit Concrete(Base& f): fwd(f) {}
// ... other member functions elided
bool foo() const override { return /* some calculation */ && fwd.foo(); }
private:
Base& fwd;
};
so that I can construct a series of instances like this:
Concrete c1(Base::getHeadInstance());
Concrete c2(c1);
Concrete c3(c2);
so that c3 can make decisions and possibly defer to c2, which in turn could defer to c1 and so on like the Chain of Responsibility pattern.
The problem is that c2 and c3 are not constructed correctly and their fwd member always refers to Base::getHeadInstance().
What is going wrong here and what is the fix for this?
Update:
It doesn't matter what the static member returns. Pretend it returns an instance of this:
class Head: public Base {
public:
Head() = default;
private:
bool foo() const override { return true; }
};
Base& Base::getHeadInstance(){ static Head head; return head; }
I've had this same problem before. It boils down to overload resolution on your custom constructor Derived(Base&) vs the implicitly defined copy constructor Derived(const Derived&);, where the implicit copy constructor simply wins. Deleting it does not fix this, it still participates in overload resolution (but it does stop the wrong thing from happening silently).
Here is a reduced example:
struct Base
{
virtual ~Base();
};
struct Derived : Base
{
Derived(Base&);
Derived(const Derived&); // Implicitly or explicitly declared in any case.
};
Derived getDerived();
void test()
{
Derived d1 = getDerived();
Derived d2(d1); // copies
}
https://godbolt.org/z/aoJFlC
There are several ways to get the code to do what you want the way you've written it (see other answers), but I would like to point out that you should take special care to save the next reader of your code from this same confusion you had. A cast to Base&, repurposed copy constructor semantics or something like using Derived(Base*); will all raise questions in future readers. You can try to solve that through documentation, but chances are somebody misses that and becomes confused. I would suggest making the intent as explicit and visible as possible, for example like this:
enum class ConstructFromBase { Tag };
struct Derived : Base
{
Derived(Base&, ConstructFromBase);
Derived(const Derived&) = delete;
};
Derived getDerived();
void test()
{
Derived d1 = getDerived();
Derived d2(d1, ConstructFromBase::Tag);
}
https://godbolt.org/z/QfeuAM
That should communicate the intent very clearly and costs virtually nothing. (There are many other ways to write and name such a tag, mine is probably not the most canonical...)
You have an implicit copy constructor you need to get rid of:
Concrete(const Concrete& c) = delete;
and you'll have to cast your c1 and c2
Concrete c1(Base::getHeadInstance());
Concrete c2((Base&)c1);
Concrete c3((Base&)c2);
Your other option is to template the constructor:
template<typename T>
Concrete(T& f): fwd(f) {}
and then your original code would work (Yay!).
Concrete c1(Base::getHeadInstance());
Concrete c2(c1);
Concrete c3(c2);
You just need to provide you own copy constructor that does what you want. Adding
Concrete(Concrete& c): fwd(c) {}
Will then make
Concrete c1(Base::getHeadInstance());
Concrete c2(c1);
Concrete c3(c2);
have c1.fwd == Base::getHeadInstance(), c2.fwd == c1, and c3.fwd == c2
Another possible solution is to avoid using references; even if I admit it is not isomorphic.
class Concrete : public Base {
public:
explicit Concrete(Base* f) : fwd(*f) {
// possibly you want to assert precondition? assert(f)?
}
private:
Base& fwd; // I would prefer Base* here...
};
In that way, you don't risk to call the implicit copy constructor of Concrete; without override o delete anything.
Concrete c1(&Base::getHeadInstance());
Concrete c2(&c1);
Concrete c3(&c2);

copy and swap idiom with pure virtual class

I am trying to implement virtual class with pure virtual method and 'copy and swap' idiom, but I've encountered some problems. Code won't compile because I am creating instance in the assign operator of the class A which contains pure virtual method.
Is there a way how to use pure virtual method and copy and swap idiom?
class A
{
public:
A( string name) :
m_name(name) { m_type = ""; }
A( const A & rec) :
m_name(rec.m_name), m_type(rec.m_type) {}
friend void swap(A & lhs, A & rhs)
{
std::swap(lhs.m_name, rhs.m_name);
std::swap(lhs.m_type, rhs.m_type);
}
A & operator=( const A & rhs)
{
A tmp(rhs);
swap(*this, tmp);
return *this;
}
friend ostream & operator<<( ostream & os,A & x)
{
x.print(os);
return os;
}
protected:
virtual void print(ostream & os) =0;
string m_type;
string m_name;
};
class B : A
{
public:
B(string name, int att) :
A(name),
m_att(att)
{
m_type="B";
}
B( const B & rec) :
A(rec),
m_att(rec.m_att) {}
friend void swap(B & lhs, B & rhs)
{
std::swap(lhs.m_att, rhs.m_att);
}
B & operator=( const B & rec)
{
B tmp(rec) ;
swap(*this, tmp);
return *this;
}
private:
virtual void print(ostream & os);
int m_att;
};
Error message:
In member function ‘A& A::operator=(const A&)’:|
error: cannot declare variable ‘tmp’ to be of abstract type ‘A’|
because the following virtual functions are pure within ‘A’:|
virtual void A::print(std::ostream&)|
As your compiler informs you, you cannot create a variable of abstract type. There is no way of dancing around that.
This leaves you three main options:
Stop using pure virtual functions
First, you could just get rid of the pure virtual methods and provide a little stub in each of them that calls std::terminate, which would obviously break compile time detection of whether all (former) pure virtual methods are overridden in all derived classes.
This will cause slicing, since it will only copy the base class and everything that makes out the derived class is lost.
Use a stub class w/o pure virtual functions
Similar to that, you could create a derived class that implements all virtual methods with simple stubs (possibly calling std::terminate), and is used only used as a "instantiatable version of the base class".
The most important part to implement for this class would be a constructor that takes a const reference to the base class, so you can just use it instead of copying the base class. This example also adds a move constructor, because I am a performance fetishist.
This causes the same slicing problem as the first option. This may be your intended result, based on what you are doing.
struct InstantiatableA : public A {
InstantiatableA(A const& rhs) : A(rhs) { }
InstantiatableA(A&& rhs) : A(::std::move(rhs)) { }
void print(ostream&) override { ::std::terminate(); }
};
A& A::operator=(InstantiatableA rhs) {
using ::std::swap;
swap(*this, rhs);
return *this;
}
Note: This is really a variable of type A, although I said it could not be done. The only thing you have to be aware is that the variable of type A lives inside a variable of type InstantiatableA!
Use a copy factory
Finally, you can add a virtual A* copy() = 0; to the base class. Your derived class B will then have to implement it as A* copy() override { return new B(*this); }. The reason dynamic memory is necessary is because your derived types may require arbitrarily more memory than your base class.
You're just facing the fact that inheritance works awkwardly with copy semantics.
For instance, imagine you found a trick to pass the compiling phase, what would mean (following example uses assignment but the issue is the same with a copy) :
// class A
// a class B : public A
// another class C : public A inheriting publicly from A
// another class D : public B inheriting publicly from B
B b1;
C c1;
D d1;
// Which semantic for following valid construction when copy/assignment is defined in A ?
b1 = c1;
b1 = d1;
A &ra = b1;
B b2;
// Which semantic for following valid construction when copy/assignment is defined in A ?
ra = b2;
ra = c1;
ra = d1;
CRTP is a choice:
template<typename swappable>
struct copy_swap_crtp{
auto& operator=(copy_swap_crtp const& rhs){
if (this==std::addressof(tmp))
return *this;
swappable tmp{rhs.self()};
self().swap(tmp);
return *this;
};
auto& operator=(copy_swap_crtp && rhs){
self().swap(rhs.self());
return *this;
};
protected:
auto& self(){return *static_cast<swappable*>(this);};
//auto& self()const{return *static_cast<swappable const*>(this);};
};
user class:
struct copy_swap_class
: copy_swap_crtp<copy_swap_class>
{
copy_swap_class(copy_swap_class const&);
void swap(copy_swap_class&);
};
cheers,
FM.
The compiler is right. The class A is abstract class, therefore you can not create instances of it in the operator=.
In B, you just declared the print function, but you didn't implement it. Meaning, you will get linking errors.
By implementing it, it compiles fine (if we ignore various warnings) :
void B::print(ostream & os )
{
os << m_att;
}
by the way :
B inherits privately from A, is that what you wanted?
order of initialization in A's copy constructor is wrong
you initialized m_type in A's constructor's body and not in the initialization list

Virtual Function During Construction Workaround

I've got a base class that has a virtual function. I want to call that class during the construction because I want the function called for each of the derived classes. I know I can't call a virtual function during construction, but I can't think of an elegant (i.e., avoid repeating code) solution.
What are some work arounds to calling a virtual function during construction?
The reason I want to avoid this is because I don't want to have to create constructors that just call the base class.
class A {
public:
A() {
read();
}
// This never needs to be called
virtual void read() = 0;
}
class B:A {
public:
B():A() { };
read() { /*Do something special for B here.*/ }
}
class C:A {
public:
C():A() { };
read() { /*Do something special for C here.*/ }
}
PS: The Python way of doing this is simply to raise NotImplementedError in A::read(). I'm returning to C++ and I'm more rusty than I thought.
The FAQ perspective.
This is a Frequently Asked Question.
See the C++ FAQ item titled “Okay, but is there a way to simulate that behavior as if dynamic binding worked on the this object within my base class's constructor?”.
It’s very often a good idea to check the FAQ (and generally, googling or altavista’ing) before asking.
The question as “Derived class specific base initialization”.
To be clear, while the literal question above is
“What are some work arounds to calling a virtual function during construction?”
it is evident that what’s meant is
“How can a base class B be designed so that each derived class can specify part of what goes on during B construction?”
A major example is where C style GUI functionality is wrapped by C++ classes. Then a general Widget constructor might need to instantiate an API-level widget which, depending on the most derived class, should be a button widget or a listbox widget or whatever. So the most derived class must somehow influence what goes on up in Widget’s constructor.
In other words, we’re talking about derived class specific base construction.
Marshall Cline called that “Dynamic Binding During Construction”, and it’s problematic in C++ because in C++ the dynamic type of an object during class T construction and destruction, is T. This helps with type safety, in that a virtual member function is not called on a derived class sub-object before that sub-object has been initialized, or its initialization has started. But a major cost is that DBDI (apparently) can’t be done in a way that is both simple and safe.
Where the derived class specific init can be performed.
In the question the derived class specific action is called read. Here I call it derived_action. There are 3 main possibilities for where the derived_action is invoked:
Invoked by instantiation code, called two-phase construction.
This essentially implies the possibility of having a mostly unusuable not fully initialized object at hand, a zombie object. However, with C++11 move semantics that has become more common and accepted (and anyway it can be mitigated to some extent by using factories). A main problem is that during the second phase of construction the ordinary C++ protection against virtual calls on uninitialized sub-objects, due to dynamic type changes during construction, is not present.
Invoked by Derived constructor.
For example, derived_action can be invoked as an argument expression for the Base constructor. A not totally uncommon technique is to use a class template to generate most derived classes that e.g. supply calls of derived_action.
Invoked by Base constructor.
This implies that knowledge of derived_action must be passed up to the constructor, dynamically or statically. A nice way is to use a defaulted constructor argument. This leads to the notion of a parallel class hierarchy, a hierarchy of derived class actions.
This list is in order of increasing sophistication and type safety, and also, to the best of my knowledge, reflects the historical use of the various techniques.
E.g. in Microsoft’s MFC and Borland’s ObjectWindows GUI early 1990’ libraries two-phase construction was common, and that kind of design is now, as of 2014, regarded as very ungood.
This is the factory method approach, putting the factory into the base class:
class A {
public:
virtual void read() = 0;
template<class X> static X* create() {X* r = new X;X->read();return X;}
virtual A* clone() const = 0;
};
class B : public A {
B():A() { };
friend class A;
public:
void read() { /*Do something special for B here.*/ }
B* clone() const {return new B(*this);}
};
class C : public A {
C():A() { };
friend class A;
public:
void read() { /*Do something special for C here.*/ }
C* clone() const {return new C(*this);}
};
Added a clone-method with covariant return type as a bonus.
Using CRTP:
class A {
public:
// This never needs to be called
virtual void read() = 0;
virtual A* clone() const = 0;
};
template<class D, class B> struct CRTP : B {
D* clone() {return new D(*this);}
static D* create() {return new D();}
};
class B : public CRTP<B, A> {
B() { };
public:
void read() { /*Do something special for B here.*/ }
};
class C : public CRTP<C, A> {
C() { };
public:
void read() { /*Do something special for C here.*/ }
};
One way to achieve this, would be simply to delegate it to another class (that is perhaps a friend) and can be sure to be called when fully constructed.
class A
{
friend class C;
private:
C& _c; // this is the actual class!
public:
A(C& c) : _c(c) { };
virtual ~A() { };
virtual void read() = 0;
};
class B : public A
{
public:
B(C& c) : A(c) { };
virtual ~B() { };
virtual void read() {
// actual implementation
};
};
class C
{
private:
std::unique_ptr<A> _a;
public:
C() : _a(new B(*this)) { // looks dangerous? not at this point...
_a->read(); // safe now
};
};
In this example, I just create a B, but how you do that can depend on what you want to achieve and use templates on C if necessary, e.g:
template<typename VIRTUAL>
class C
{
private:
using Ptr = std::unique_ptr<VIRTUAL>;
Ptr _ptr;
public:
C() : _ptr(new VIRTUAL(*this)) {
_ptr->read();
};
}; // eo class C
The workaround is to call the virtual function after construction. You can then couple the two operations (construction + virtual call) in factory function. Here is the basic idea:
class FactoryA
{
public:
A *MakeA() const
{
A *ptr = CreateA();
ptr->read();
return ptr;
}
virtual ~FactoryA() {}
private:
virtual A *CreateA() const = 0;
};
class FactoryB : public FactoryA
{
private:
virtual A *CreateA() const { return new B; }
};
// client code:
void f(FactoryA &factory)
{
A *ptr = factory.MakeA();
}
As mentioned by Benjamin Bannier, you can use CRTP (a template which defines the actual read() function.) One problem with that method is that templates have to always be written inline. That can at times be problematic, especially if you are to write really large functions.
Another way is to pass a function pointer to the constructor. Although, in a way, it is similar to calling the function in your constructor, it forces you to pass a pointer (although in C++ you could always pass nullptr.)
class A
{
public:
A(func_t f)
{
// if(!f) throw ...;
(*f)();
}
};
class B : A
{
public:
B() : A(read) {}
void read() { ... }
};
Obviously, you have the "can't call other virtual functions" problem within the read() function and any function it calls. Plus, variable members of B are NOT yet initialized. That is probably a much worst problem in this case...
For that reason, writing it this way is safer:
B() : A()
{
read();
}
However, in cases like that, that may be the time when you an some for of init() function. That init() function can be implemented in A() (if you make it accessible: i.e. use public A when deriving) and that function can call all the virtual functions as expected:
class A
{
public:
void init()
{
read();
}
};
class B : public A
{
public:
...
};
I know a lot of people say that an init() function is evil because people who create a B object now need to know to call it... but there isn't much else you can do. That being said, you could have a form of factory, and that factory can do the init() call as required.
class B : public A
{
public:
static B *create() { B *b(new B); b->init(); return b; }
private:
B() { ... } // prevent creation without calling create()
};

Calling the constructor of the base class after some other instructions in C++

As far as I know it is not possible to call the constructor of the base class. The only way I know is this:
MyClass::MyClass(/* args */) : Base(/* args */)
{
// ...
}
but this would invoke the constructor at the beginning.
Is there any way to call it somewhere else in the constructor? Something like this:
MyClass::MyClass(/* args */)
{
// ... instructions
Base::Base(/* args */);
// ... other_instructions
}
According to this What are the rules for calling the superclass constructor? question I understand there is no way but I read here and I guessed it was possible, but if I try I get:
error: invalid use of 'class Base'.
Am I doing something wrong? Is it possible to do this some way or is there any other possible solution to this need?
Thanks!
EDIT: I understand I forgot a key point: the base class is part of a framework, and therefore it would be good not to have to modify it, if possible.
If the base class constructor takes at least one argument, you could use a helper function like this:
int DoStuffBeforeCtorAndForwardInt(int arg, Foo foo)
{
DoStuff(arg, foo);
return arg;
}
MyClass::MyClass(int arg, Foo foo)
: Base(DoStuffBeforeCtorAndForwardInt(arg, foo))
{
// ...
}
If you want to default-initialize the base class, you could use the copy-ctor to copy a default initialized base class instance:
Base DoStuffBeforeCtorAndReturnDefaultBase(int arg, Foo foo)
{
DoStuff(arg, foo);
return Base();
}
MyClass::MyClass(int arg, Foo foo)
: Base(DoStuffBeforeCtorAndReturnDefaultBase(arg, foo))
{
// ...
}
Or, if Base doesn't have to be the first base class, you could derive MyClass from a helper class:
MyClass::MyClass(/* ... */)
: DoStuffHelperClass(/* ... */),
Base(/* ... */)
{
// ...
}
All of the above require that the "stuff" you do does not depend on the object that's about to be initialized (i.e. the functions can't safely be member functions and you cannot safely pass this as an argument to them either).
That means you can do some logging or similar, but then again you could also do that after the base class has been initialized.
(EDIT except with the DoStuffHelperClass solution, you can of course have members in DoStuffHelperClass, access them and what not)
Although I have to say that I can't recall ever using/needing/wanting something like that. It's quite probable that there is another (preferable) solution for what you're trying to do.
Use the base-from-member idiom to run your code before the ctor of the "real" base class (which is Base):
struct Base {
Base(string, int);
};
struct DerivedDetail {
DerivedDetail() {
value = compute_some_value();
value += more();
value += etc();
other = even_more_code(value);
}
string value;
int other;
};
struct Derived : private DerivedDetail, Base {
Derived() : Base(value, other) {}
// In particular, note you can still use this->value and just
// ignore that it is from a base, yet this->value is still private
// within Derived.
};
This works even if you don't have actual members you want in DerivedDetail. If you give more specifics on what you must do before the Base's ctor, then I can give a better example.
The base class is always fully constructed before construction of your own class begins. If you need to make a change to the state of the base class, you have to do that explicitly after it has been constructed.
Example:
MyClass::MyClass()
{
// Implicit call to Base::Base()
int result = computeSomething();
Base::setResult(result);
// ...
}
Besides the already written solutions, you can also use a static constructor function and make the contructor of MyClass private.
class QtBase{
// ...
};
class MyClass : public QtBase{
public:
// copy ctor public
MyClass(MyClass const& other);
static MyClass Create(/*args*/){
// do what needs to be done
int idata;
float fdata;
// work with idata and fdata as if they were members of MyClass
return MyClass(idata,fdata); // finally make them members
}
static MyClass* New(/*args*/){
int idata;
float fdata;
// work with idata and fdata as if they were members of MyClass
return new MyClass(idata,fdata); // finally make them members
}
private:
// ctor private
MyClass(int a_idata, float a_fdata)
: idata(a_idata)
, fdata(a_fdata)
{}
int idata;
float fdata;
};
Now you would have to create instances of MyClass either as:
MyClass obj = MyClass::Create(/*args*/);
or
MyClass* ptr = MyClass::New(/*args*/);
no, because it will not be type safe.
consider you have: a class A and a variable A.var.
now consider B inherits from A, and uses var before A was initialized. you will get a run time error! the language wants to prevent this, thus superclass constructor must be initialized first.
No, you can't do it that way, as other have described in their previous answers.
Your only chance is composition, IOW that MyClass uses Base class as a member field:
class MyClass {
public:
/** the methods... */
private:
Base* _base;
};
so you can initialize _base later, when you have the needed info. I don't know if this can apply to your scenario, anyway.
No. It is not possible, because the order of constructor calls is strictly defined by the standard. Base class ctor has to be executed before the derive class ctor can be executed.