Reputation: 311
I'm trying to get my derived class(humanplayer) to make a variable member function of abstract(Vector) equal to "hi" so that I can display that but the compiler acts all weird and says EXC_BAD_ACCESS(code=EXC_I386_GPFLT).
Here is my header file:
#ifndef __testing_more_stuff__vector__
#define __testing_more_stuff__vector__
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Vector{//abstract class
public:
void setName(string name_holder);
virtual void test()=0;
protected:
string name;
};
class player{//base class that has an aggregation relationship with vector
protected:
Vector *molo;
};
class humanplayer:public player//derived class of player
{
public:
void play();
};
#endif
Here is my implementation file:
#include "vector.h"
void Vector::setName(string name_holder)
{
name=name_holder;
cout<<name<<endl;
}
void humanplayer::play()
{
molo->setName("hi");//since humanplayer inherits from player it should be able to set name to hi and print it out
}
Here is my test/main file:
#include "vector.h"
int main()
{
humanplayer x;
x.play();
}
Upvotes: 0
Views: 147
Reputation: 41220
In humanplayer::play()
you say:
molo->setName("hi")
However, molo
is of type Vector
, which is an abstract base class pointer.
A few things:
Vector
molo
to something like molo = new VectorDerivedClass()
molo
to nullptr
, and you don't check for it. Your string
assignment is undefined behavior.You MUST have a concrete derived class from Vector
. And you MUST instantiate the pointer with new
before you try to do anything with it.
The nice thing about polymorphism is that you are allowed to have a pointer to an abstract base class. This pointer can be assigned to any dynamically allocated derived class. Effectively, the pointer enforces an interface; derived classes are guaranteed to implement the pure virtual functions in the abstract base (and inherit those you provide a definition for in the base).
The downside is that you do have to inherit from the class, and calls to virtual
functions have to go through the virtual table (vtable), which is an indirection and is a tad bit slower.
Upvotes: 1