Inheritance with base class constructor with parameters
The problem is that the base class foo
has no parameterless constructor. So you must call constructor of the base class with parameters from constructor of the derived class:
public bar(int a, int b) : base(a, b)
{
c = a * b;
}
Pass Inherited Class Constructor Arguments to Base Constructor Arguments
A far more OO standards compliant way to do this is to use an abstract property. This means the base class has defined the property but the extending classes must implement it. This also means you cannot directly create an instance of vehicle
, instead you must create one of the derived types.
abstract class vehicle
{
vehicle() { }
public abstract string Model { get; }
}
// Inherited classes
class tesla : vehicle
{
private readonly string model = "Model S"; // This is unchanging
public override string Model { get { return model; }}
}
class ferrari : vehicle
{
public override string Model { get { return "458 Spider"; }}
}
The only time you really want to be passing values from derived constructors to base constructors is when those values are actively used in the base class. This is a normally when you've overridden a base constructor, or you are using a dependency injection or dependency resolution pattern. The base class should not act as an aggregation of information from the derived class.
Pass inherited arguments to base class constructor, then do something in derived class constructor
One way you could do this is to make a variadic template constructor in the derived class that passes all of its arguments to the base class. Then you can do whatever additional stuff you want in the body of that constructor. That would look like
struct Base
{
Base (int) {}
Base(int, int) {}
//...
};
struct Derived : Base
{
template<typename... Args>
Derived(Args&&... args) : Base(std::forward<Args>(args)...) // <- forward all arguments to the base class
{
// additional stuff here
}
};
Inheritance and base constructor
The basic answer to your question is yes. Your derived classes must define a constructor, specifically they must do so when no default constructor is available on the base class.
This is because base class constructors are always fired when derived classes are created (in fact, they are fired first). If you don't have a constructor to pass the base class constructor its required arguments, the compiler doesn't know how to handle this.
In your case, something like
public Dragon(string _name, int _health, int _attack, int _level)
:base(_name, _health, _attack, _level)
{
}
Will get you started. You may need (and can have) other parameters for your Dragon
of course. You can also pass literals into the base constructor (so you don't need to parameterize the Dragon
one with all base class arguments).
public Dragon(string _name)
:base(_name, 1000, 500, 10)
{
}
The only requirement is that an existing base class constructor is used.
Can the constructor of a derived class have more parameters than the constructor of its base class?
You have to specify how to call the constructor on the base class using the base()
constructor call:
public Range(float _maxhp, float _damage, float _attack, float _attackSpeed)
: base(_maxhp, _damage)
{
// handle _attack and _attackSpeed
}
How to avoid repeating base class constructor parameters in derived class in C++?
When it comes to strict OOP, such issues are usually handled by encapsulating the parameters in structs:
struct HumanData {
int pAge,
bool pSex,
double pSize,
double pPower,
bool pFly,
bool pHeal
}
Alternatively, you could make a construct to create a SuperHuman on a MetaHuman base.
Just a hint, as I see you're trying some game dev.
Usually wrapping attributes in structures, 'pays off a lot'.
So make your SEX a bool based enum (i know, a little bit overkill :)). You can read about based class enums in C++0x here: https://smartbear.com/blog/closer-to-perfection-get-to-know-c11-scoped-and-ba/?feed=develop
You will get extra strongly typed class data, with almost no performance impact.
As a side note: Are you absolutely sure you need to make your class hierarchy so steep? As Stroustrup said "Don’t immediately invent a unique base for all of your classes. Typically, you can do better without it for many/most classes." - which is quite accurate.
C++ is not C#/Java - forcing it to be so, will only make it rebel.
C++ How can I call superclass constructor with two parameters from derived class constructor with one parameter?
Simply by calling the constructor like this:
class square : public shape {
public:
square(int d): shape(d, d)
{
}
};
It is important that you call the constructor before the body of the constructor of the derived class. You should also initialize your member variables before the constructor body.
If you will not do that, the default initialization of all objects will be done and after that a assignment will be done as second step. In your example, you first try to use default initialization of your parent class which is not possible, because you have no default constructor.
More on this topic can be found here:
http://en.cppreference.com/w/cpp/language/initializer_list
Class constructor inheritance using `extends` with passed in arguments
The parent
and child
are class objects and they dont have relation each other. From your code, when you call let child = new Child()
, you did nothing with the x
, y
, w
and h
in your Child
constructor.
The Classes are templates, the inheritance means you copy the parent's methods implementation.
You can just think the Parent
and Child
classes are different each other - just the Child
class has all the methods that the Parent
has.
When you inherit a class, you need to pass the parameters that the Parent
class needs in its constructor.
You can fix it like below:
class Parent {
constructor(x, y, w, h) {
this.x = x; //if I put values directly here it works
this.y = y;
this.w = w;
this.h = h;
}
}
class Child extends Parent {
constructor(x, y, w, h) {
super(x, y, w, h); // <- Passing the parameters
this.pt1 = {x: this.x, y: this.y};
this.pt2 = {x: this.x + this.w, y: this.y};
this.pt3 = {x: this.x + this.w, y: this.y + this.h};
this.pt4 = {x: this.x, y: this.y + this.h};
}
}
let parent = new Parent(300, 50, 50, 200);
let child = new Child(300, 50, 50, 200); // <- pass the values
console.log(child.pt1)
console.log(child.pt3)
Inherited class needs parameter for base class constructor
Your subclass doesn't need a constructor with arguments, but all constructors need to call the base class constructor properly.
As the base class doesn't have a default constructor, you need to do something like this:
class Query : public ConnectDB{
private:
public:
Query(): ConnectDB("") { ... }
};
The thing is, unless you want to hardcode the value input to ConnectDB
, your base class probably needs a constructor with a string parameter so you can forward it to ConnectDB's
constructor.
Related Topics
How to Delete a File Which Is Locked by Another Process in C#
Razor: Declarative HTML Helpers
How to Execute Process Commands (Or Similar) Using a Universal Windows Platform (Uwp) App
Run Process as Administrator from a Non-Admin Application
C# - Capturing the Mouse Cursor Image
Can't Convert Value Type Array to Params Object[]
How to Execute a Command in a Remote Computer
Addeventhandler Using Reflection
Loading a Full Hierarchy from a Self Referencing Table with Entityframework.Core
Updating an Observablecollection in a Separate Thread
Can a C# Lambda Expression Have More Than One Statement
System.Drawing.Image to Stream C#
Windows Forms Progressbar: Easiest Way to Start/Stop Marquee
Force Xmlserializer to Serialize Datetime as 'Yyyy-Mm-Dd Hh:Mm:Ss'
Why Explicit Implementation of a Interface Can Not Be Public
Mono Https Webrequest Fails with "The Authentication or Decryption Has Failed"