How to Initialize objects with overloaded constructors using different files - c++

I have tried literally everything to try to initialize the constructor so that when I create an object and pass the parameters in, it wont give me a crazy negative number, but it's still not working!
To test that it works I used the getHp and attack function. So for example, if I say Hero Hi(100, 200, 300, 400), then I say Hi.getHP(), it should be 100(the first parameter)...
//main.cpp
int main()
{
Hero Me(100,20,30,40);//Created using overloaded constructor
Monsters m(100,16,18,20);//creates a monster object and uses overloaded constructor
to initialize
cout << "\ntest1\n";
Me.getHp();//expecting 100
Me.getAttack();//expecting w.e is in parameters
m.getHp();//expecting 100
m.getAttack();//same as hero
cin.sync();
cin.get();
return 0;
}
Here is the rest of my code, in case you need it. I also left out headers and such for simpler code.
//Characters.h
class Characters
{
private:
int level;
int hp;
int attack;
int defense;
protected:
Characters(); // zero everything by default
Characters(int, int, int, int); // populate explicitly
~Characters();
public:
int getAttack() const { return attack; }
int getDefense() const { return defense; }
int getHp() const { return hp; }
int getlevel() const { return level; }
void setAttack(int);
void setDefense(int);
void setStrength(int);
void setHp(int);
void setlevel(int);
void damageTaken(int);
};
//Characters.cpp
Characters::Characters() : level(0), hp(0), attack(0), defense(0) {}
//
//Characters::Characters(int seed)
//{
// // NB. your code still doesn't initialize hp, strength etc.
// // it also logs level before initializing it, so that will be garbage
//}
//Characters::Characters(int hit, int lvl, int att, int def)
// : level(lvl), hp(hit), attack(att), defense(def){}
Hero::Hero(int newHp, int newLevel, int newAttack, int newDef)
: Characters(newHp, newLevel, newAttack, newDef)
{
cout << "Hero created using Overloaded function!\n";
HeroHp = newHp;
cout << "Hp is: "<< HeroHp << endl;
Herolevel = newLevel;
cout << "level is: " << Herolevel << endl;
HeroAttack = newAttack;
cout << "Attack is: " << HeroAttack << endl;
HeroDefense = newDef;
cout << "Defense is: " << HeroDefense << endl;
// logging goes here
// note that you don't need HeroLevel etc. at all any more, just use level
}
Monsters::Monsters(int newHp, int newLevel, int newAttack, int newDef)
: MonsterHp(newHp), Monsterlevel(newLevel), MonsterAttack(newAttack)
, MonsterDefense(newDef)//initialize list
{
cout << "Monster created using Overloaded function!\n";
MonsterHp = newHp;
cout << "Hp is: "<< MonsterHp << endl;
Monsterlevel = newLevel;
cout << "level is: " << Monsterlevel << endl;
MonsterAttack = newAttack;
cout << "Attack is: " << MonsterAttack << endl;
MonsterDefense = newDef;
cout << "Defense is: " << MonsterDefense << endl;
}
Characters::~Characters()
{
cout << "Character has been destroyed!\n";
}
void Characters::setAttack(int att)
{
attack = att;
}
void Characters::setDefense(int def)
{
defense = def;
}
void Characters::setHp(int health)
{
hp = health;
}
void Characters::damageTaken(int damage)
{
hp -= damage;
}
void Characters::setlevel(int lvl)
{
level = lvl;
}
//Monsters.h
class Monsters:
public Characters //Hero
{
private:
int Monsterlevel;
int MonsterHp;
int MonsterStrength;
int MonsterAttack;
int MonsterDefense;
public:
Monsters(int, int, int, int); //explicit
~Monsters();
};
//Monsters.cpp
Monsters::~Monsters()
{
cout << "\nMonster Destroyed";
}
//Hero.h
class Hero:
public Characters
{
private:
int Herolevel;
int HeroHp;
int HeroStrength;
int HeroAttack;
int HeroDefense;
public:
//Hero();
Hero(int, int, int, int);
~Hero();
};
//Hero.cpp
Hero::~Hero()
{
cout << "Hero destroyed!\n";
}

HeroHp in the Hero class and hp in the Characters class are separate variables. The constructor for Hero never intializes hp, which is the variable that is returned by getHp.
You probably want to eliminate the HeroXXX variables in the Hero class and use the corresponding ones in the Characters base class.

It works fine if I uncomment Characters constructor: http://coliru.stacked-crooked.com/view?id=261944b9b1304c3ed9d76e69b2318ee2-ad7854d9cfd7979d567ca413f0830b65
Are you sure you were compiling with success? You left some warnings around that might have deceived you... A very good reason for removing always all of your warnings.

Related

The code does not assign value to an inherited function parameter and do not call function

The code does not reduce the default health value, just prints default value out. It does not call GetName() and GetHealth() functions that are inside the TakeDamage() function. The code can run without problem. Screen out put is below the code. Where is the problem here? How do I fix?
#include<iostream>
using namespace std;
class Creature
{
public:
Creature();
void setName(string name);
void TakeDamage(float Damage);
string GetName();
float GetHealth();
private:
string Name;
float Health;
};
class Voldemort : public Creature
{
private:
void AvadaKedavra();
public:
void MakeMagic();
};
void Creature::setName(string name)
{
Name = name;
cout << name << endl;
}
int main()
{
Voldemort Anger;
Anger.MakeMagic();
Anger.setName("Harry Potter");
return 0;
}
Creature::Creature()
{
cout << "A creature has been created" << endl;
Health=100;
}
string Creature::GetName()
{
return Name;
}
float Creature::GetHealth()
{
return Health;
}
void Creature::TakeDamage(float Damage)
{
float Total;
Total = Health - Damage;
if (Total <= 0.f)
{
cout << GetName() << " has died" << endl;
}
else
{
Health -= Damage;
}
cout << "Health: " << Health << endl;
cout << "Health: " << GetHealth() << endl;
}
void Voldemort::MakeMagic()
{
AvadaKedavra();
}
void Voldemort::AvadaKedavra()
{
TakeDamage(100);
}
Screen:
A creature has been created
has died
Health: 100
Health: 100
Harry Potter
if (Total <= 0.f)
{
cout << GetName() << " has died" << endl;
}
else
{
Health -= Damage;
}
You don't change the health when Total is less or equal 0, which is the case when you call TakeDamage(100)

I need help (write and read function) c++

The program is working in this way. But I need to change the price system. I need to use priceRead and priceWrite.
priceRead (): double
priceWrite (in _price: double): void
priceRead: price is a function to read the property.
priceWrite (double): price property is a function of writing.
Sorry for bad english. :(
#include <iostream>
#include <string.h>
using namespace std;
class shoes{
protected:
int size;
string colour;
char sex;
string brand;
public: shoes(int _size, string _colour, char _sex, string _brand)
:size(_size),colour(_colour), sex(_sex), brand(_brand)
{cout << "shoe configurator" << endl;}
~shoes(){ }
void shoesInf();
};
class storage{
protected:
int number;
int maxsize;
int minsize;
public: storage(int _number, int _maxsize, int _minsize)
:number(_number),maxsize(_maxsize),minsize(_minsize)
{cout << "store configurator" << endl;}
~storage(){ }
void storageInf();
};
void shoes::shoesInf()
{
cout << "Size :" << size << endl;
cout << "Colour :" << colour << endl;
cout << "Sex :" << ((sex=='M')?"Man":"Woman") << endl;
cout << "Brand:" << brand << endl;
}
void storage::storageInf()
{
cout << "Number :" << number << endl;
cout << "Max size :" << maxsize << endl;
cout << "Min size :" << minsize << endl;
}
class Store: public storage{
private: int number;
int maxsize;
int minsize;
public: Store(int _number, int _maxsize, int _minsize)
:storage(_number,_maxsize,_minsize)
{cout << "storage INF" << endl;}
};
class Nike: public shoes{
private: double price;
public: Nike(int _size, string _colour, char _sex, string _brand,
double _price):shoes(_size,_colour,_sex,_brand),price(_price)
{cout << "Shoes INF" << endl;}
void shoesInf()
{
((shoes*)this)->shoesInf();
cout << "Price :" << price << endl;
}
};
class Lacoste: public shoes{
private: double price;
public: Lacoste(int _size, string _colour, char _sex, string _brand,
double _price):shoes(_size,_colour,_sex,_brand),price(_price)
{cout << "Shoes INF" << endl;}
void shoesInf()
{
((shoes*)this)->shoesInf();
cout << "Price:" << price<< endl;
}
};
int main(int argc, char** argv) {
Store*sh=new Store(1,50,15);
sh->storageInf();
Nike *sh2=new Nike(38,"Blue",'F',"Nike",100);
sh2->shoesInf();
Lacoste *sh3=new Lacoste(40,"Yellow",'M',"Lacoste",350);
sh3->shoesInf();
return 0;
}
class Shoes
{
private:
int size;
string colour;
char sex;
string brand;
double price;
public:
Shoes(int _size, string _colour, char _sex, string _brand, double _price) :
size(_size), colour(_colour), sex(_sex), brand(_brand), price(_price)
{}
void writePrice(double newPrice)
{
price = newPrice;
}
void readPrice()
{
cout << price << endl;
}
};
Notes:
All shoes have a price, so why not just put it in the base class?
Brand is defined by the brand string, all shoes are the same, so no need to derive a new class for each brand.
No need to have an empty destructor.
Also, without this redefinition of price when deriving, you don't have to redefine shoeInf everytime you want to derive from Shoe.
One more thing: Start class names with CapitalLetters (in that style!).

What is this error LNK2019 and 1120 [duplicate]

This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 9 years ago.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
//In this section I create the class HotelRoom
class HotelRoom
{
protected:
HotelRoom(){}
char room_Number[4];
char* guestName;
double rate;
public:
HotelRoom(char Num[], double daily, char* name);
HotelRoom(const HotelRoom &);
~HotelRoom();
int Get_Capacity();
int Get_Status();
double Get_Rate();
const char* Get_Number();
const char* Get_Guest();
int Change_Status(int Stat);
};
HotelRoom::HotelRoom(char Num[], double daily, char* name)
{
strcpy_s(room_Number, 4, Num);
guestName = new char[strlen(name) + 1];
strcpy_s(guestName, 20, name);
rate = daily;
}
HotelRoom::HotelRoom(const HotelRoom& room_r)
{
strcpy_s(room_Number, room_r.room_Number);
guestName = new char[strlen(room_r.guestName) + 1];
strcpy_s(guestName, 20, room_r.guestName);
rate = room_r.rate;
}
HotelRoom::~HotelRoom()
{
cout << endl << endl;
cout << "Decunstructor Activated." << endl;
delete[] guestName;
}
double HotelRoom::Get_Rate()
{
return rate;
}
const char* HotelRoom::Get_Number()
{
return room_Number;
}
const char* HotelRoom::Get_Guest()
{
return guestName;
}
class DerivedGuestRoom : public HotelRoom
{
public:
DerivedGuestRoom(int max, int stat, int nights);
DerivedGuestRoom(const DerivedGuestRoom&);
~DerivedGuestRoom();
protected:
int capacity;
int status = 0; //0 if unoccupied
int days;
};
DerivedGuestRoom::DerivedGuestRoom(int max, int stat, int nights) : capacity(max), status(stat), days(nights)
{
cout << "data members set";
}
DerivedGuestRoom::~DerivedGuestRoom()
{
cout << "\ndecunstrucor";
}
class DerivedMeetingRoom : public HotelRoom
{
public:
DerivedMeetingRoom(int seat, int stat);
DerivedMeetingRoom(const DerivedMeetingRoom&);
~DerivedMeetingRoom();
protected:
int seats;
int status; //1 if booked for meeting 0 otherwise
};
DerivedMeetingRoom::DerivedMeetingRoom(int seat, int stat) : seats(seat), status(stat)
{
cout << "data members set";
}
DerivedMeetingRoom::~DerivedMeetingRoom()
{
cout << "\ndecunstrucor";
}
void Display_info(HotelRoom&);
HotelRoom* Create_Hotel();
int main()
{
cout << setprecision(2)
<< setiosflags(ios::fixed)
<< setiosflags(ios::showpoint);
HotelRoom* Hotel_Rooms[200];
int count = 0;
char response;
cout << endl;
cout << "Do you want to enter information about a hotel room?(Y/N): ";
response = cin.get();
cin.get();
while (toupper(response) == 'Y' && count < 10)
{
Hotel_Rooms[count] = Create_Hotel();
++count;
cout << endl;
cout << "Do you want to enter information about a hotel room?(Y/N): ";
response = cin.get();
cin.get();
}
//Display the accounts created
for (int i = 0; i < count; ++i)
Display_info(*Hotel_Rooms[i]);
for (int i = 0; i < count; ++i)
delete Hotel_Rooms[i];
cout << endl;
system("PAUSE");
return 0;
}
void Display_info(HotelRoom& room)
{
cout << "\n\nGuest's Name: " << room.Get_Guest() << endl << endl;
cout << "\nYour room number is " << room.Get_Number() << endl << endl;
cout << "\nDaily rate is: " << room.Get_Rate() << endl << endl;
cout << endl;
cout << endl;
}
HotelRoom* Create_Hotel()
{
//These are the variables that will be holding data then passed through objects
char roomNumber[4];
char guestName[20];
double dailyRate = 89.00;
HotelRoom* room_ptr;
//This portion asks for user input
cout << "\nEnter Guest information\n\n";
cout << "Enter the room number: ";
cin.getline(roomNumber, 4);
cout << "Enter the guest's name: ";
cin.getline(guestName, 20);
cout << endl;
cin.get(); //Clears input buffer
room_ptr = new HotelRoom(roomNumber, dailyRate, guestName);
return room_ptr;
}
I took out HotelRoom(); from parent class constructor and I removed from the child class constructors. I Now only have this error:
LearningOOP.exe has triggered a breakpoint.
Which I have never encountered this so not sure what it means.
You declared a default constructor:
class HotelRoom
{
public:
HotelRoom();
}
and there is no implementation for that default constructor method. You can change to:
class HotelRoom
{
public:
HotelRoom() {}
}
or implement HotelRoom:HotelRoom { } in your cpp file.
You haven't defined your default constructor for the HotelRoom class.
class HotelRoom
{
protected:
char room_Number[4];
char* guestName;
double rate;
public:
HotelRoom(); //< Not defined!
HotelRoom(char Num[], double daily, char* name);
HotelRoom(const HotelRoom &);
~HotelRoom();
int Get_Capacity();
int Get_Status();
double Get_Rate();
const char* Get_Number();
const char* Get_Guest();
int Change_Status(int Stat);
};
An "Unresolved external symbol" linker error means that you've declared and used a piece of code in your application, but you haven't defined it before using it.
EDIT (Based on your follow up comment below):
You can't take the constructor out because it's needed in other parts of your code. See this line in your code:
DerivedGuestRoom::DerivedGuestRoom(int max, int stat, int nights) : HotelRoom(), capacity(max), status(stat), days(nights)
// ^---------^
// |
// Using the default constructor.
DerivedMeetingRoom::DerivedMeetingRoom(int seat, int stat) : HotelRoom(), seats(seat), status(stat)
// ^---------^
// |
// And again here!
You either need to remove implement the default constructor for the HotelRoom class, or add parameters to your DerivedMeetingRoom and DerivedGuestRoom class constructors so that you can use the HotelRoom(char Num[], double daily, char* name) constructor.

How to initialize instances of classes?

//main.cpp
#include "Monsters.h"
#include "Hero.h"
#include "Monsters.h"
#include "Characters.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
When i created my object it took those parameters and initialised them to it right?
So why when i called their methods, it returned a different value?
For example, I initialized them here while created my object at the same time:
Hero Me(100,20,30,40);
Monsters m(100,16,18,20);//creates a monster object and uses overloaded constructor to initialize
Me.getHp();//expected 100, but got a long negative random number
m.getHp();//expected 100, but got a long negative random number also
//Why must i use setHp() and setAttack() when i already initialized them with the constructor?
Me.setAttack(89);
Me.setHp(100);
m.setAttack(40);
m.setHp(100);
cout << "\nAttacking!\n";
while ((Me.getHp() > 0) && (m.getHp() > 0))
{
cout << "\nYour hp is: " << Me.getHp() << endl;
cout << "The enemy's hp is: "<< m.getHp() << endl;
cout << "\nThe monster has attacked you!\n";
cout << "You received " << m.getAttack() << " damage;" << endl;
Me.damageTaken(m.getAttack());
if(Me.getHp() > 0)//Check if still alive
{
cout << "\nYour hp is now: " << Me.getHp() << endl;
//cout << "Enemy hp is: "<< m.getHp() << endl;
cout << "\nNow you attacked!\nYou have dealt "<< Me.getAttack() << " Damage" << endl;
m.damageTaken(Me.getAttack());
if(m.getHp() > 0)//Check if still alive
{
cout << "Enemy hp is now: " << m.getHp() << endl;
cout << "\nAttacking again!\n";
}
}
}
if ((Me.getHp() > 0) && (m.getHp() <= 0))
cout <<"\nCongratulations! You killed the enemy!" << endl;
else if ((Me.getHp() <= 0) && (m.getHp() > 0))
cout << "You have died!" << endl;
cin.sync();
cin.get();
return 0;
}
Here's the rest of the code in case you need it:
//Hero.h
#pragma once
#include "Characters.h"
class Hero:
public Characters
{
private:
int Herolevel;
int HeroHp;
int HeroStrength;
int HeroAttack;
int HeroDefense;
public:
//Hero();
Hero(int, int, int, int);
~Hero();
};
//Hero.cpp
#include "Monsters.h"
#include "Hero.h"
#include "Characters.h"
#include <iostream>
using namespace std;
//Hero::Hero()
//{
// cout << "HOLA! Hero Created using normal constructor\n";
//}
Hero::Hero(int newHp, int newLevel, int newAttack, int newDef)
: HeroHp(newHp), Herolevel(newLevel), HeroAttack(newAttack), HeroDefense(newDef)
{
cout << "Hero created using Overloaded function!\n";
HeroHp = newHp;
cout << "Hp is: "<< HeroHp << endl;
Herolevel = newLevel;
cout << "level is: " << Herolevel << endl;
HeroAttack = newAttack;
cout << "Attack is: " << HeroAttack << endl;
HeroDefense = newDef;
cout << "Defense is: " << HeroDefense << endl;
}
Hero::~Hero()
{
cout << "Hero destroyed!\n";
}
//Monsters.h
#pragma once
#include "Characters.h"
class Monsters:
public Characters //Hero
{
private:
int Monsterlevel;
int MonsterHp;
int MonsterStrength;
int MonsterAttack;
int MonsterDefense;
public:
//Monsters();
Monsters(int, int, int, int);
//Monsters(int);
~Monsters();
};
//Monsters.cpp
#include "Monsters.h"
#include "Hero.h"
#include "Characters.h"
#include <iostream>
using namespace std;
Monsters::Monsters(int newHp, int newLevel, int newAttack, int newDef)
: MonsterHp(newHp), Monsterlevel(newLevel), MonsterAttack(newAttack), MonsterDefense(newDef)
{
cout << "Monster created using Overloaded function!\n";
MonsterHp = newHp;
cout << "Hp is: "<< MonsterHp << endl;
Monsterlevel = newLevel;
cout << "level is: " << Monsterlevel << endl;
MonsterAttack = newAttack;
cout << "Attack is: " << MonsterAttack << endl;
MonsterDefense = newDef;
cout << "Defense is: " << MonsterDefense << endl;
}
Monsters::~Monsters()
{
cout << "\nMonster Destroyed";
}
//Characters.h
#pragma once
class Characters
{
private:
int level;
int Hp;
int Strength;
int Attack;
int Defense;
public:
Characters();
Characters(int);
Characters(int, int, int, int);
~Characters();
int getAttack();
int getDefense();
int getStrength();
int getHp();
int getLevel();
void setAttack(int);
void setDefense(int);
void setStrength(int);
void setHp(int);
void setlevel(int);
void damageTaken(int);
};
//Characters.cpp
#include "Characters.h"
#include "Hero.h"
#include "Monsters.h"
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
Characters::Characters()
{
cout << "\nCharacter has been created!\n";
}
Characters::Characters(int random)
{
cout << "Level " << level << " character created with: \n";
srand ((unsigned)time(0));
random = rand() % 10 + 1;
//setlevel(int random);
level = random;
}
Characters::~Characters()
{
cout << "Character has been destroyed!\n";
}
void Characters::setAttack(int att)//get Character left over hp
{
Attack = att;
}
void Characters::setDefense(int def)//get Character left over hp
{
Defense = def;
}
void Characters::setStrength(int str)//get Character left over hp
{
Strength = str;
}
void Characters::setHp(int health)//get Character left over hp
{
Hp = health;
}
void Characters::damageTaken(int damage)//get Character left over hp
{
Hp -= damage;
}
void Characters::setlevel(int lvl)//get Character left over hp
{
level = lvl;
}
int Characters::getAttack()
{
//cout << "Your attack is: " << Attack << endl;
return Attack;
}
int Characters::getDefense()
{
//cout << "Your defense is: " << Defense << endl;
return Defense;
}
int Characters::getStrength()
{
//cout << "Your strength is: " << Strength << endl;
return Strength;
}
int Characters::getHp()
{
//cout << "Your hp is: " << Hp << endl;
return Hp;
}
int Characters::getLevel()
{
//cout << "Your level is: " << level << endl;
return level;
}
How to initialize instances of classes?
You need to correctly initialize your base classes by calling their constructor, passing on the relevant arguments. Maybe it is easier to illustrate this with a simpler example:
class Foo
{
public:
explicit Foo(int i) : foo_i(i) {}
int getFoo() const { return foo_i; }
private:
};
class Bar : public Foo
{
public:
explicit Bar(int i) : Foo(i) // calls Foo(int) constructor, setting Foo::foo_i
{}
};
#include <iostream>
int main()
{
Bar b(42);
b.getFoo(); // prints 42
}
Hero inherits Characters, including all its data members (level, hp, etc.).
So, it doesn't need to add its own HeroLevel, HeroHP etc. You're just duplicating data (and work).
Now, it also doesn't initialize the base class members - the default constructor for Characters doesn't even zero them, so their values are undefined.
You should be looking for something like this:
class Characters
{
private:
int level;
int hp;
int strength;
int attack;
int defense;
protected:
Characters(); // zero everything by default
Characters(int); // randomly generate everything
Characters(int, int, int, int); // populate explicitly
public:
int getAttack() const { return Attack; }
// etc.
};
Characters::Characters() : level(0), hp(0), strength(0), attack(0), defense(0) {}
Characters::Characters(int seed) {
// NB. your code still doesn't initialize hp, strength etc.
// it also logs level before initializing it, so that will be garbage
}
Characters::Characters(int hit, int lvl, int att, int def)
: level(lvl), hp(hit), attack(att), defense(def)
{
// you only pass 4 attributes, what should strength be?
}
and finally:
Hero::Hero(int newHp, int newLevel, int newAttack, int newDef)
: Characters(newHp, newLevel, newAttack, newDef)
{
// logging goes here
// note that you don't need HeroLevel etc. at all any more, just use level
}
You should really try to understand the basics of this before designing an entire class hierarchy - see juanchopanza's answer for a clear example. A smaller example would also have been much easier to paste, read and understand.

Object of abstract class type "Rectangle" is not allowed

//QuizShape.h
#ifndef QUIZSHAPE_H
#define QUIZHAPE_H
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class QuizShape
{
protected:
//outer and inner symbols, and label
char border, inner;
string quizLabel;
public:
//base class constructor with defaults
QuizShape(char out = '*', char in = '+', string name = "3x3 Square")
{
border = out;
inner = in;
quizLabel = name;
cout << "base class constructor, values set" << endl << endl;
};
//getters
char getBorder() const
{ return border; }
char getInner() const
{ return inner; }
string getQuizLabel() const
{ return quizLabel; }
//virtual functions to be defined later
virtual void draw( ) = 0;
virtual int getArea( ) = 0;
virtual int getPerimeter( ) = 0;
};
class Rectangle : public QuizShape
{
protected:
//height and with of a rectangle to be drawn
int height, width;
public:
//derived class constructor
Rectangle(char out, char in, string name,
int h = 3, int w = 3):QuizShape(out, in, name)
{
height = h;
width = w;
cout << "derived class constructor, values set" << endl << endl;
}
//getters
int getHeight() const
{ return height; }
int getWidth() const
{ return width; }
//*********************************************
virtual void draw(const Rectangle &rect1)
{
cout << "draw func" << endl;
cout << rect1.height << endl;
cout << rect1.getWidth() << endl;
cout << rect1.getQuizLabel() << endl;
}
virtual int getArea(const Rectangle &rect2)
{
cout << "area func" << endl;
cout << rect2.getInner() << endl;
cout << rect2.getBorder() << endl;
}
virtual int getPerimeter(const Rectangle &rect3)
{
cout << "perim func" << endl;
cout << rect3.height << endl;
cout << rect3.getWidth() << endl;
cout << rect3.getQuizLabel() << endl;
}
//************************************************
};
#endif
These are the class types so far.
//QuizShape.cpp
#include "QuizShape.h"
This currently does nothing but bridge the files.
//pass7.cpp
#include "QuizShape.cpp"
int main()
{
Rectangle r1('+', '-', "lol", 4, 5);
cout << r1.getHeight() << endl;
cout << r1.getWidth() << endl;
cout << r1.getInner() << endl;
cout << r1.getBorder() << endl;
cout << r1.getQuizLabel() << endl;
system("pause");
return 0;
}
The code will not compile due to the fact that Rectangle is supposedly an abstract class, and when hovering over the declaration of r1 in main, I receive the error
"Object of abstract class type "Rectangle" is not allowed".
I have checked other answers on this site and others and have not come across something that solves the problem.
NOTE: I understand that the statements for virtual functions ending in =0; cause the class to become an abstract one. QuizShape SHOULD be abstract. I have defined the virtual functions in Rectangle and yet it remains an abstract class.
How can I modify the virtual functions Rectangle class so that Rectangle is no longer abstract?
Your methods int the abstract class QuizShape are:
virtual void draw( ) = 0;
virtual int getArea( ) = 0;
virtual int getPerimeter( ) = 0;
but in Rectangle they take const Rectangle &rect1 as parameter so you shadowing the methods and not overriding the abstract one at all. You need to have methods in Rectangle with the same signature as the ones in the abstract base class.
The overridden methods must have the exact same signature, in the derived class you have given them arguments.