Inheritance Beginner C++ Issue [duplicate] - c++

This question already has answers here:
no default constructor exists for class x (inheritance) C++
(2 answers)
Closed 8 years ago.
I seem to be having a problem with Inheritance. Whenever I try to override a function in my Character.cpp file I get an error stating:'No default constructor exists for class Character'. I'm fairly new to c++ and I don't get why the error was appearing. What I want to do is basically override the GetFierceAttack() of the default Character class to be stronger for the child class which is called Ogre. I was wondering if I was using 'virtual' correctly.
My Character.h file
#ifndef CHARACTER_H
#define CHARACTER_H
#include <time.h>
#include <cstdlib>
class Character
{
protected:
int Health, LightAttack, FierceAttack, Damage;
public:
Character(int health, int lAttack, int fAttack, int damage);
~Character();
public:
int GetHealth() {return Health;}
int GetLightAttack() {return (rand()%5)+10;}
virtual int GetFierceAttack() {return (rand()%5)+10;}
void DeductDamage(int Damage);
};
//Overrides Fierce Attack
class Ogre:public Character
{
public:
Ogre(int health, int lAttack, int fAttack, int damage);
int GetFierceAttack() {return (rand()%10)+20;}
};
#endif
My Chacter.cpp file
#include "Character.h"
//Constructor
Character::Character(int health, int lAttack, int fAttack, int damage)
{
Health = health;
LightAttack = lAttack;
FierceAttack = fAttack;
Damage;
}
//Destructor
Character::~Character()
{
}
void Character::DeductDamage(int Damage)
{
Health -= Damage;
if(Health < 0)
{
Health = 0;
}
}
//Constructor
Ogre::Ogre(int health, int lAttack, int fAttack, int damage) //Here's the error
{
}
//Destructor
Ogre::~Ogre()
{
}

When you define constructor for class by yourself, you are overriding the default implementation.
So you need to provide default constructor as
class Character
{
public:
Character(){}
//----------your code-----//
}
Similarly for your destructor problem you first decalre destructor in class and then define it in .cpp file.
class Ogre:public Character
{
public:
~Ogre();
}

When you declare a non-default constructor for a class, the compiler does not generate a default constructor anymore.
So you have to provide your own.

When you call the constructor on a derived class, what happens is this:
the base object gets constructed first
any variables in the initialisation list get initialised
the body of the (derived) constructor is executed
If you do not specify a different constructor, the default constructor will be used for (1). You are getting a compiler error because you have no default constructor.
To specify a different constructor, do something like this:
Ogre::Ogre(int health, int lAttack, int fAttack, int damage) : Character (health, lAttack, fAttack, damage)
{
// body of constructor
}
Then the instance of the constructor that matches those parameters will be called instead. Since you have defined that, you won't get an error.
As for the error on the destructors, firstly, as others have said, you can't override the destructor without declaring it in the class. So you could add ~Ogre() to your class definition. However, you're not currently doing anything in your destructor body, so why are you redefining it at all? Just leave it as the default destructor.

Related

"No default constructor exists " even though I don't need it [duplicate]

This question already has answers here:
no default constructor exists for class x (inheritance) C++
(2 answers)
Closed 3 years ago.
I'd like to ask as to why does my compilator say "No default constructor exists for class Object" even though I don't need it anywhere in that class.
I am supposed to NOT use a default constructor (it's explicitly said that I only need a parametrized one with parameter id, full assignment can be found on this link)
I've tried to think of the reason why it needs default constructor but I just can't see it. Like, not even in header I need constructor for object.
I've been searching google too but it doesn't answer my question either, or if it does I just can't understand it and apply it for my example.
This is my Object.h
#pragma once
#ifndef OBJECT_H
#define OBJECT_H
class Object
{
public:
Object(int aId);
virtual ~Object() {};
int getId() const;
double getX() const;
double getY() const;
void setX(double aX);
void setY(double aY);
private:
int id;
double x;
double y;
};
#endif //!OBJECT_H
This is my Object.cpp
#include "Object.h"
Object::Object(int aId)
{
this->id = aId;
}
int Object::getId() const
{
return this->id;
}
double Object::getX() const
{
return this->x;
}
double Object::getY() const
{
return this->y;
}
void Object::setX(double aX)
{
this->x = aX;
}
void Object::setY(double aY)
{
this->y = aY;
}
This is the header file for the class that I am getting the error in
#pragma once
#ifndef STATIC_OBJECT_H
#define STATIC_OBJECT_H
#include "Object.h"
enum class ObstacleType { Rock, SmallFlower, BigFlower };
class StaticObject : public Object {
public:
StaticObject(int aId, ObstacleType aObstacleType);
ObstacleType& getObstacleType();
private:
ObstacleType obstacleType;
};
#endif // !STATIC_OBJECT_H
And here on the line 4 starting with a bracket I get the error saying "No default constructor exists in class Object" even though I don't need it there, even if I don't put anything in the block it keeps saying that.
#include "StaticObject.h"
StaticObject::StaticObject(int aId, ObstacleType aObstacleType)
{ // <-- compilator error shows here
Object* obj = new Object(aId);
this->obstacleType = aObstacleType;
}
ObstacleType& StaticObject::getObstacleType() {
return this->obstacleType;
}
Your StaticObject constructor is not calling any non-default Object constructor, so the default constructor will be called for the base class, thus your current code does need a default Object constructor.

C++ setting value of derived parameterlized ctor [duplicate]

This question already has answers here:
What are the rules for calling the base class constructor?
(10 answers)
Closed 7 years ago.
Hey guys. I dont know how i suppose to do about setting values to derived classes ctor. And here is my code. I remember something like that build in my class. But i know that we can write something like that build ( xxx():yyy(){,,,};).
Check the main's second object.
#include <iostream>
using namespace std;
class vehicle
{
protected:
string brand;
int wheelNumber;
double maxSpeed=0;
public:
vehicle(){cout<<"default ctor for vehicle"<<endl;}
vehicle(string br1, int wn1, double ms1)
{brand=br1; wheelNumber=wn1; maxSpeed=ms1;}
void setbrand(string br){brand=br;}
string getbrand(string br){return brand;}
void setWN(int wn){wheelNumber=wn;}
int getWN(int wn){return wheelNumber;}
void setMaxS(double ms){maxSpeed=ms;}
double getMaxS(double ms){return maxSpeed;}
~vehicle(){cout<<"dtor for vehicle."<<endl;}
};
class car: public vehicle
{
private:
int numberOfDoors;
string fuelType;
public:
car(){cout<<"default ctor for car"<<endl;}
car(int nOD,string fT){numberOfDoors=nOD; fuelType=fT;}
void setnOD(int nOD){numberOfDoors=nOD;}
int getnOD(int nOD){return numberOfDoors;}
void setfT(string fT){fuelType=fT;}
string getfT(string fT){return fuelType;}
void printFeatures()
{
cout<<endl;
cout<<"brand:"<<brand<<endl;
cout<<"wheelNumber:"<<wheelNumber<<endl;
cout<<"MaxSpeed:"<<maxSpeed<<endl;
cout<<"NumberOfDoors:"<<numberOfDoors<<endl;
cout<<"FuelType:"<<fuelType<<endl<<endl;
}
~car(){cout<<"dtor for car."<<endl;}
};
int main()
{
car *cc;
cc= new car;
cc->setbrand("bmw");
cc->setfT("diesel");
cc->setMaxS(333.25);
cc->setWN(4);
cc->setnOD(6);
cc->printFeatures();
delete cc;
car *xx;
xx= new car;
car(5,"gasoline"):vehicle("mercedes",4,489.12);//Part that i cant figure it out.
xx->printFeatures();
delete xx;
}
The ctor(...):base(...){} syntax is used when defining the derived class constructor, not when instantiating an object. So change the constructor to car to this:
car(int nOD,string fT, string br1, int wn1, double ms1): vehicle(br1, wn1, ms1) {
numberOfDoors=nOD; fuelType=fT;
}
And instantiate your car object like this:
xx= new car(5,"gasoline", "mercedes",4,489.12);
Even better, take advantage of C++'s member-initialization syntax to define your constructors:
vehicle(string br1, int wn1, double ms1)
:brand(br1), wheelNumber(wn1), maxSpeed(ms1)
{}
// ...
car(int nOD,string fT, string br1, int wn1, double ms1)
: vehicle(br1,wn1, ms1), numberOfDoors(nOD), fuelType(fT)
{}
You need to code this into the constructor to get this to work. When you derive from a class the constructor of that derived class needs to take in the parameters for the base constructor and its own construction.
class Base
{
int foo;
public:
Base(int f) : foo(f) {};
};
class Derived : public Base
{
int bar;
public:
Derivced(int f, int b) : Base(f), bar(b) {}
^^^^^^^ ^^^^^^^^^
construct the base part constrcut the derived part
};
So for you example the constructor for car would become:
car(string br1, int wn1, double ms1, int nOD,string fT) : vehicle(br1, wn1, ms1),
numberOfDoors(nOD),
fuelType(fT) {}
Since you are allocating instance of class car which is derived class so it is calling both the ctors. First it will call the ctor of class 'vehicle' and then 'car'. [Read the order of calling ctor in case inheritance]

C++ calling an inherited constructor

I have a header file, "Item.h", which "Sword.h" inherits, like this:
#ifndef SWORD_H
#define SWORD_H
#include "Item.h"
class Sword: public Item {
public:
Sword(int damage);
~Sword();
};
#endif
My Item.h is this:
#ifndef ITEM_H
#define ITEM_H
class Item{
public:
int damage;
Item(int damage);
int GetDamage();
};
#endif
And then I have a file, "Sword.cpp", that I want to call the Item constructor from (this is the Item.cpp):
#include "Item.h"
Item::Item(int damage)
{
this->damage = damage;
}
int Item::GetDamage()
{
return damage;
}
I basically want Sword.cpp to be a child class of Item.cpp, so that I can use Item's functions, and set variables such as Damage from Sword.cpp. I've been told there is no way to inherit constructors in C++ though, so how could I do this? Some answers seem to use the explicit keyword, but I can never get it to work.
Any help please?
You can actually inherit constructors. It is all-or nothing though, you can't select which ones. This is how you do it:
class Sword: public Item {
public:
using Item::Item;
~Sword();
};
If you are stuck with a pre-C++11 compiler, then you need to declare the constructor and implement it yourself. This would be the implementation in Sword.cpp:
Sword::Sword(int damage) : Item(damage) {}
You don't inherit the constructor because the constructor has the same name as the class (and obviously parent and child must have different names). But you can use the parent's constructor in the child's constructor
Sword()
: Item(3) // Call the superclass constructor and set damage to 3
{
// do something
}
You can define the Sword constructor the following way
Sword(int damage) : Item( damage ) {}
Also it would be better if the destructor of Item were virtual and data member damage should have access control protected. For example
class Item{
protected:
int damage;
public:
Item(int damage);
virtual ~Item() = default;
int GetDamage();
};
You can call the parent's constructor from your derived class's constructor like this:
Sword(int damage):
Item(damage)
{
}

declaration and definition of constructor of class and print out private and public variables?

I am having hard time, I am learning classes in C++ now, here is problem I have, I have to declare and define constructor, i dont know what wrong i am doing i tried but could not get the result please help
#include <iostream>
using namespace std;
class exercise
{
public:
//declaration: constructor of class exercise
int public_var;
int get_private_var();
private:
int private_var;
};
//definition: constructor of class exercise
int exercise::get_private_var()
{
return private_var;
}
int main()
{
exercise object(2,3);
int pub_var = object.public_var;
int pri_var = object.get_private_var();
cout << pub_var <<' '<<pri_var<<endl;
return 0;
}
A sample constructor would be:
class exercise
{
public:
exercise(int,int);
int public_var;
int get_private_var();
private:
int private_var;
};
//Constructor definition
exercise::exercise(int a, int b)
{
public_var = a;
private_var = b
}
//rest of member functions
In order to declare a constructor you should
class exercise
{
public:
//declaration: constructor of class exercise
exercise();
int public_var;
int get_private_var();
private:
int private_var;
};
In order to implement (usually in .cpp file)
you should:
exercise::exercise()
{
//your code here
}
good luck
get_private_var is not a constructor. It's function that is called when you do object.get_private_var() - it's just a typical member function.
The constructor is the function that gets called when you construct your object (makes sense, right?). In your case, it would be used when you do:
exercise object(2,3);
This line constructs an exercise object called object and passed the values 2 and 3 to its constructor. It looks like you want to assign those values to the public_var and private_var members.
First you need to declare your constructor:
class exercise
{
public:
exercise(int, int); //declaration: constructor of class exercise
int public_var;
int get_private_var();
private:
int private_var;
};
As you can see, the constructor is declared just like any other member function, except it does not have a return type. That makes sense since the return type is clearly the class itself. Here I have specified two arguments.
Now we need to define the constructor, similar to how you have defined get_private_var, but again with no return type:
exercise::exercise(int x, int y)
{
public_var = x;
private_var = y;
}
And then you're done. This constructor simply assigns the values that are passed to it to the public and private members.
However, there is a slightly better way of implementing this constructor, using a member initialization list:
exercise::exercise(int x, int y)
: public_var(x), private_var(y)
{ }
Here is how you build a class with constructor
class a
{
public:
int pubvar;
a() //default constructor
{
pubvar =1;
privar =2;
}
a(int one, int two) //constructor with intializing
{
pubvar = one;
privar = two;
}
private:
int privar;
}
now default initialization is
a myclass;
and initialize with your variables is
a myclass(4,2);
hope that helps

C++ Default Constructor Not Found

I'm having a problem with some code in Visual C++ 2010 Express. I'm trying to make a class that has a constructor that accepts an argument which has a default value. Here's a short program that shows what I'm trying to achieve:
//Class declaration
class Class {
private:
int mValue;
public:
Class(int);
int GetValue();
};
Class::Class(int val=1) : mValue(val)
{
}
int Class::GetValue()
{
return mValue;
}
int main()
{
Class test;
cout << test.GetValue() << endl;
}
Now this seems to work fine. If I replace Class test with Class test(10), say, mValue is initialised correctly.
However, in a second program I'm trying to do exactly the same thing. I have a class defined like this:
namespace mobs {
Class Monster {
private:
mHitPoints;
public:
Monster(int);
int GetHitPoints() const;
};
}
with the implementation of the functions like this:
namespace mobs {
Monster::Monster(int hp=10) : mHitPoints(hp)
{
}
int Monster::GetHitPoints() const
{
return mHitPoints;
}
}
but when I try to declare a class and use the GetHitPoints() function like so:
mobs::Monster testmonster;
cout << testmonster.GetHitPoints() << endl;
Visual C++ tells me that "no default constructor exists for class mobs::Monster". Why is this?
The default value belongs in the declaration, not the definition. Move the =10 to your header file:
Monster(int hp = 10).
In the implementation, you don't even need the default value. I usually use:
Monster::Monster(int hp /*=10*/)
just to make it clear there's a default.
The constructor is ambigious. that's why.
if you have two constructors
Monster(){}
Monster(x=10){}
and you make a call
Monster m();
How should the compiler know whether you mean the first or second constructor
Instead Define it as follows
class Class {
private:
int mValue;
public:
Class(int val) :mValue(val){}
Class() :mValue(1){}
};