I want to use the virtual function in my program. However, VSCode keeps telling me errors in the redefinition of the function.
This is my error message:
exp8_2.cpp:29:7: error: redefinition of 'float Mammal::getweight() const'
float Mammal::getweight() const
^~~~~~
exp8_2.cpp:25:23: note: 'virtual float Mammal::getweight() const' previously defined here
virtual float getweight() const {};
^~~~~~~~~
It seems like the virtual function could not be overrode
Below is my code:
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
class Mammal
{
protected:
float weight;
public:
Mammal(float wei)
{
this->weight=wei;
}
Mammal(){};
~Mammal(){};
virtual void Speak() const {};
virtual float getweight() const {};
};
float Mammal::getweight() const
{
return this->weight;
}
class Dog:public Mammal
{
protected:
float height;
public:
Dog(float wei,float hei):Mammal(wei)
{
this->height=hei;
}
Dog(){};
~Dog(){};
void Speak()const {};
float getweight () const{};
};
void Dog::Speak() const
{
cout<<"Woof!"<<endl;
};
float Dog::getweight() const
{
return this->weight;
};
int main()
{
Mammal mal(500);
Dog doggo(500,1.5);
Mammal *point;
point=&mal;
point->getweight();
point->Speak();
point=&doggo;
point->getweight();
point->Speak();
}
I could provide more info if the problem is not on my code but VScode.