class CarPart
{
public:
CarPart(): name(""), price(0) {}
virtual int getPrice() = 0;//{return price;}
protected:
int price;
string name;
};
class Tire: public CarPart
{
public:
virtual int getPrice() {return price;}
Tire(): CarPart(), name("Tire"), price(50)
{}
};
Visual 2010 tells me name and price are not members of deriv, but they are inherited (error c2614). What am I doing wrong ?
CPP. 4) An abstract class can have constructors. For example, the following program compiles and runs fine.
Constructor is automatically called when the object is created. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can derive from several(two or more) base classes. The constructors of inherited classes are called in the same order in which they are inherited.
When classes are inherited, the constructors are called in the same order as the classes are inherited. If we have a base class and one derived class that inherits this base class, then the base class constructor (whether default or parameterized) will be called first followed by the derived class constructor.
Constructor is always called by its class name in a class itself. A constructor is used to initialize an object not to build the object. As we all know abstract classes also do have a constructor.
You cannot initialize members that is not an immediate member of your class. n
is not an immediate member of deriv
, it's an immediate member of base
.
However, n
is accessible to deriv
, so you can always assign it in your deriv
constructor, but you should really initialize it in the base
constructor.
Also, you can't have virtual
constructors. Did you mean to use virtual
destructors?
class base
{
public:
base() : n(0) {} // Are you sure you don't want this?
virtual void show() = 0;
protected:
int n;
};
class deriv : public base
{
public:
deriv()
{
n = 0;
}
virtual void show() {}
};
EDIT (A response to the OP's edit): You don't need virtual methods for this:
class CarPart
{
public:
CarPart(const char* newName, int newPrice) : name(newName), price(newPrice) {}
const std::string& GetName() const { return name; }
int GetPrice() const { return price; }
private:
std::string name;
int price;
};
class Tire : public CarPart
{
public:
Tire() : CarPart("Tire", 50) {}
};
Assuming that all your CarPart
s has to have a name and a price, this should be more than sufficient.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With