Reputation: 199
Okay, so I have been working on a homework project and found a way that will let me finish the homework and get it turned in, but it is still bothering me.
I have a base class that is dynamically allocating some other classes, and a Derived class.
//header
class Base
{
Private:
Type *type_ptr;
Public:
Base();
Base(Type &new_type);
//getters and setters
}
class Derived : public Base
{
Private:
Type2 *type2_ptr;
Public:
Derived();
Derived(Type, Type2) : Base(Type);
}
What I want to figure out is what this should look like in my .cpp file, instead of doing it in-line like so,
Derived(Type new_type, Type2 new_type2): Base(new_type){
type2_ptr = new Type2(new_type2);
};
edit: if I try something like the above in my .cpp that I get errors like this, always two of them too...
undefined reference to `vtable for Derived'
undefined reference to `vtable for Derived'
Upvotes: 3
Views: 2925
Reputation: 154047
You've not shown everything. In the code you've shown, there should be no vtable, since there are no virtual functions (and the class isn't polymorphic, regardless of the inheritance.
Supposing that there are virtual functions, you should almost certainly add a virtual destructor to Base.
Beyond that, the definition in the .cpp file should be:
Derived::Derived(Type new_type, Type2 new_type2)
: Base(new_type)
, type2_ptr(new Type2(new_type2))
{
}
Add the Derived:: in front of your definition, and there's nothing in the code you expose which should cause problems. You really should provide a complete example of the code which does cause the problem; otherwise, we can just guess.
Upvotes: 0
Reputation: 4795
header:
/* Base same as yours */
class Derived : public Base
{
Private:
Type2 *type2_ptr;
Public:
Derived();
Derived(Type&, Type2);
}
cpp:
Base::Base(): type_ptr(NULL)
{
// implementation goes here
}
Base::Base(Type &new_type): type_ptr(&new_type)
{
// implementation goes here
}
Derived::Derived()
{
// implementation goes here
}
Derived::Derived(Type& new_type, Type2 new_type2): Base(new_type),
type2_ptr(new Type2(new_type2))
{
// implementation goes here
}
note thet new_type
is reference, not local variable in Derived
, so variable passed to Derived must be in proper scope!
Upvotes: 3
Reputation: 361812
Outside of class you need to use Derived::
for all constructors and functions!
Derived::Derived(Type new_type, Type2 new_type2): Base(new_type)
{//^^^^^^^^^ note this
type2_ptr = new Type2(new_type2);
};
Also consider using initialization-list
as much as possbible. Here is one example!
Derived::Derived(Type new_type, Type2 new_type2): Base(new_type), type2_ptr(new Type2(new_type2))
//^^^^ note this!
{
};
Upvotes: 1