My question is very similar like other's, but a bit different. I have a sample code:
class B1 {
private :
int * ptr;
public:
B1() : a{ 1 } { ptr = new int{ 2 }; }
B1(const B1& other) : a{ other.a } { ptr = new int{ *other.ptr }; }
~B1() { delete ptr; }
int a;
virtual void smthing() = 0;
};
class D : B1 {
public:
D(int i) : B1{} {}
D(const D& a) : B1{ a } {}
void smthing() { return; };
};
int main() {
D d { 3 };
D dd { d };
return 0;
}
I am using vs2015, and this code is works, but gives me error: object of abstract class type "B1" is not allowed...
If I remove this line D(const D& a) : B1{ a } {}, the base class copy constructor is called and there's no problem, but if I need the derived class copy constructor how can I make this work without error?
Thanks for the answer!
Related
While working with templates I ran into a need to make a base class constructors accessible from inherited classes for object creation to decrease copy/paste operations.
I was thinking to do this through using keyword in same manner with functions case, but that not work.
class A
{
public:
A(int val) {}
};
class B : public A
{
};
class C : public A
{
public:
C(const string &val) {}
};
class D : public A
{
public:
D(const string &val) {}
using A::A; // g++ error: A::A names constructor
};
void main()
{
B b(10); // Ok. (A::A constructor is not overlapped)
C c(10); // error: no matching function to call to 'C::C(int)'
}
So my question: Is there any way to import a base class constructors after new ones in inherited class been declared?
Or there is only one alternative to declare new constructors and call a base ones from initializer list?
Yes, Since C++11:
struct B2 {
B2(int = 13, int = 42);
};
struct D2 : B2 {
using B2::B2;
// The set of inherited constructors is
// 1. B2(const B2&)
// 2. B2(B2&&)
// 3. B2(int = 13, int = 42)
// 4. B2(int = 13)
// 5. B2()
// D2 has the following constructors:
// 1. D2()
// 2. D2(const D2&)
// 3. D2(D2&&)
// 4. D2(int, int) <- inherited
// 5. D2(int) <- inherited
};
For additional information see http://en.cppreference.com/w/cpp/language/using_declaration
Prefer initialization:
class C : public A
{
public:
C(const string &val) : A(anInt) {}
};
In C++11, you can use inheriting constructors (which has the syntax seen in your example D).
Update: Inheriting Constructors have been available in GCC since version 4.8.
If you don't find initialization appealing (e.g. due to the number of possibilities in your actual case), then you might favor this approach for some TMP constructs:
class A
{
public:
A() {}
virtual ~A() {}
void init(int) { std::cout << "A\n"; }
};
class B : public A
{
public:
B() : A() {}
void init(int) { std::cout << "B\n"; }
};
class C : public A
{
public:
C() : A() {}
void init(int) { std::cout << "C\n"; }
};
class D : public A
{
public:
D() : A() {}
using A::init;
void init(const std::string& s) { std::cout << "D -> " << s << "\n"; }
};
int main()
{
B b; b.init(10);
C c; c.init(10);
D d; d.init(10); d.init("a");
return 0;
}
No, that's not how it is done. Normal way to initialize the base class is in the initialization list :
class A
{
public:
A(int val) {}
};
class B : public A
{
public:
B( int v) : A( v )
{
}
};
void main()
{
B b(10);
}
You'll need to declare constructors in each of the derived classes, and then call the base class constructor from the initializer list:
class D : public A
{
public:
D(const string &val) : A(0) {}
D( int val ) : A( val ) {}
};
D variable1( "Hello" );
D variable2( 10 );
C++11 allows you to use the using A::A syntax you use in your decleration of D, but C++11 features aren't supported by all compilers just now, so best to stick with the older C++ methods until this feature is implemented in all the compilers your code will be used with.
class A
{
public:
A(int val) {}
A(string name) {}
};
class B : public A
{
using A::A;
};
Addition to other answers, in case there are several constuctors with the base class, and you just want to inherit some of them, you can delete the unwanted.
class B : public A
{
using A::A;
B(string) = delete;
};
Here is a good discussion about superclass constructor calling rules. You always want the base class constructor to be called before the derived class constructor in order to form an object properly. Which is why this form is used
B( int v) : A( v )
{
}
How to convert two parent pointers in c++?
This is the code.
// base class
class B {
public:
virtual ~B() {};
// other code
};
class A {
public:
virtual ~A() {};
// other code
};
// child class
class C1 : public A, B {
public:
virtual ~C1() {};
// other code
};
class C2 : public A, B {
public:
virtual ~C2() {};
// other code
};
// ...other C class
There is a std::vector<std::shared_ptr<A>> which items point to instance C1 or C2 ...Cn.
Does anyone know how to convert the vector to a std::vector<std::shared_ptr<B>>?
Your code has typos. Missing public in inheritance of B when defining C<x> breaks stuff.
After this is fixed sidecast does the job as it should:
dynamic_cast conversion - cppreference.com
b) Otherwise, if expression points/refers to a public base of the most derived object, and, simultaneously, the most derived object has an unambiguous public base class of type Derived, the result of the cast points/refers to that Derived (This is known as a "sidecast".)
// base class
class B {
public:
virtual ~B() { }
};
class A {
public:
virtual ~A() { }
};
class C1 : public A, public B {
public:
virtual ~C1() { }
};
class C2 : public A, public B {
public:
virtual ~C2() { }
};
TEST(SideCast, sigleItemCast)
{
C2 x;
A* a = &x;
auto b = dynamic_cast<B*>(a);
ASSERT_THAT(b, testing::NotNull());
}
TEST(SideCast, sideCastOfVectorContent)
{
std::vector<std::shared_ptr<A>> v { std::make_shared<C1>(), std::make_shared<C2>() };
std::vector<std::shared_ptr<B>> x;
std::transform(v.begin(), v.end(), std::back_inserter(x),
[](auto p) { return std::dynamic_pointer_cast<B>(p); });
ASSERT_THAT(x, testing::Each(testing::NotNull()));
}
Live demo
I want to create a class object, which will use a different class constructor depending on the given parameter. This is what I've tried so far.
class A{
public:
A(int x){
if (x == 1){
B(); //Initialize object with B constructor
else {
C(); //Initialize object with C constructor
}
}
};
class B : public A{
public:
B(){
//initialize
}
};
class C : public A{
public:
C(){
//initialize
}
};
int main(){
A obj(1); //Initialized with B constructor
return 0;
}
In a word, you can't do this in C++. The typical solution is to look towards the factory pattern.
class A {
public:
virtual ~A() {}
A() = default;
};
class B : A {
public:
B() = default;
};
class C : A {
public:
C() = default;
};
enum class Type
{
A,
B,
C
};
class Factory
{
public:
A* operator (Type type) const
{
switch(type)
{
case Type::A: return new A;
case Type::B: return new B;
case Type::C: return new C;
default: break;
}
return nullptr;
}
};
int main()
{
Factory factory;
A* obj = factory(Type::B); //< create a B object
// must delete again! (or use std::unique_ptr)
delete obj;
return 0;
}
When I construct an object D I need to include the constructors for A, B, and C in the initializer list. Is there any way to make it so that I don't need all three in the initializer list or not?
If I try to initialize D using only a constructor for B I get an error because I don't have a default constructor for A or C. If I add a default constructor for A and C I get issues with "i" being reinitialized with no value.
#include <iostream>
using namespace std;
class A
{
int i;
public:
A(int ii) :
i(ii)
{}
~A() { }
int getI() { return i; }
};
class B : public virtual A
{
public:
B(int ii) :
A(ii)
{ }
~B() { }
};
class C : public virtual A
{
public:
C(int ii) :
A(ii)
{ }
~C() { }
};
class D : public B, public C
{
public:
D(int ii) :
A(ii), B(ii), C(ii)
{ }
~D() { }
};
int main()
{
D d(45);
cout << d.getI() << endl;
}
If you add default constructors to A, B, and C, the implmentation of D becomes a bit simpler.
#include <iostream>
using namespace std;
class A
{
int i;
public:
A() : i(0) {}
A(int ii) : i(ii) {}
~A() { }
int getI() { return i; }
};
class B : public virtual A
{
public:
B() { }
B(int ii) : A(ii) { }
~B() { }
};
class C : public virtual A
{
public:
C() { }
C(int ii) : A(ii) { }
~C() { }
};
class D : public B, public C
{
public:
// Relies on default constructors of the other classes.
D() { }
// Relies on the default constructors of B and C.
D(int ii) : A(ii) { }
~D() { }
};
int main()
{
D d1(45);
D d2;
cout << d1.getI() << endl;
cout << d2.getI() << endl;
}
I'm afraid not. With virtual inheritance, your most-derived class must initialise the virtual base.
Read more here.
How about adding a default value to the A, B, C constructors, i.e.
A(int ii=0) :
As is talked about in Item 33 in "More Effective C++", the assignment problem is
//Animal is a concrete class
Lizard:public Animal{};
Chicken:public Animal{};
Animal* pa=new Lizard('a');
Animal* pb=new Lizard('b');
*pa=*pb;//partial assignment
However, if I define Animal as an abstract base class, we can also compile and run the sentence:*pa=*pb. Partial assignment problem is still there.
See my example:
#include <iostream>
class Ab{ private: int a;
double b;
public:
virtual ~Ab()=0;
};
Ab::~Ab(){}
class C:public Ab{
private:
int a;
double b;
};
class D:public Ab{
private:
int a;
double b;
};
int main()
{
Ab *pc=new C();
Ab *pd=new D();
*pc=*pd;
return 0;
}
Do I miss something? Then what's the real meaning of the abstract base class?
I got the answer by myself. I missed a code snippet in the book.
Use protected operator= in the base class to avoid *pa=*pb. Use abstract base class to avoid animal1=animal2.Then the only allowed expressions are lizard1=lizard2;chicken1=chicken2;
See the code below:
#include <iostream>
class Ab{
private:
int a;
double b;
public:
virtual ~Ab()=0;
protected: //!!!!This is the point
Ab& operator=(const Ab&){...}
};
Ab::~Ab(){}
class C:public Ab{
public:
C& operator=(const C&){...}
private:
int a;
double b;
};
class D:public Ab{
public:
D& operator=(const D&){...}
private:
int a;
double b;
};
int main()
{
Ab *pc=new C();
Ab *pd=new D();
*pc=*pd;
return 0;
}
The abstract base class cannot help in case of assignment because the base sub-object is not instantiated (what an abstract class would block) but is sliced off the derived object (i.e. the assignment is done between already existing base sub-objects).
To avoid the problem the only solution I can think to is
make the assignment virtual
check in the assignment that the source instance is of the correct type
In code
#include <iostream>
struct Base {
int bx;
Base(int bx) : bx(bx) {}
virtual Base& operator=(const Base& other) {
bx = other.bx;
return *this;
}
};
struct A : Base {
int x;
A(int bx, int x) : Base(bx), x(x) {}
A& operator=(const Base& other) {
const A& other_a = dynamic_cast<const A&>(other);
Base::operator=(other);
x = other_a.x;
return *this;
}
};
struct B : Base {
int x;
B(int bx, int x) : Base(bx), x(x) {}
B& operator=(const Base& other) {
const B& other_b = dynamic_cast<const B&>(other);
Base::operator=(other);
x = other_b.x;
return *this;
}
};
The dynamic_cast<const A&>(other) is the operation that will fail if the object passed to the assignment operator is not of the correct derived type (it can be a sub-derived object, but this should be logically ok for an assignment source).
As an example:
int main(int argc, const char *argv[]) {
Base *pa1 = new A(1, 2);
Base *pa2 = new A(3, 4);
Base *pb1 = new B(5, 6);
Base *pb2 = new B(7, 8);
*pa1 = *pa2; std::cout << pa1->bx << "/" << dynamic_cast<A*>(pa1)->x << "\n";
*pb1 = *pb2; std::cout << pb1->bx << "/" << dynamic_cast<B*>(pb1)->x << "\n";
std::cout << "Ok so far\n";
*pa1 = *pb1; // Runtime error here (bad cast)
return 0;
}
It doesn't matter that your base class has pure virtual functions because you haven't defined the operator= for any of the classes. So when the compiler sees this statement:
*pc=*pd;
where pc and pd are both of type Ab, it will call the default assignment operator for Ab, which will result in partial assignment. As in the following example, I get the output as "Abstract Base" which is from abstract base class:
class A {
public:
virtual void foo() =0;
virtual A& operator=(const A& rhs) {
std::cout << "Abstract Base";
return *this;
}
};
class B : public A {
public:
virtual void foo() {
std::cout << "b:foo";
}
};
class C : public A {
public:
virtual void foo() {
std::cout << "c:foo";
}
};
int main()
{
A* b = new B();
A* c = new C();
*b = *c;
return 0;
}
Since you have not handled the assignment operators in your classes, you land up in situation partial assignment as Scot clearly describes in his article.
You need to handle assignments in your classes. In current design default implicit assignment operator of Ab is called and thus all the properties of children class are lost.
To avoid this you should have an implementation like this:
class Ab{ private: int a;
double b;
public:
virtual ~Ab()=0;
virtual Ab& operator=(const Ab& rhs){cout<<"in Ab="<<endl;}
};
Ab::~Ab(){}
class C:public Ab{
C& operator=(const Ab& rhs){cout<<"in C="<<endl;
return operator=(dynamic_cast<const C&>(rhs)); }
C& operator=(const C& rhs){
cout<<"do somethin in C="<<endl;
}
private:
int a;
double b;
};
class D:public Ab{
D& operator=(const Ab& rhs){cout<<"in D="<<endl;
return operator=(dynamic_cast<const D&>(rhs)); }
D& operator=(const D& rhs){
cout<<"do somethin in D="<<endl;
}
private:
int a;
double b;
};