In the below code SecClass is inheriting 'item' from FirstClass. However when I run 'ClassC' in main both the first item and second item are 210. If I remove the pointer from the inherited class(FirstClass), it runs as it should. I'm still rather shaky with both pointers and inheritance so there's something I'm missing here...
// declaration of FirstClass
// FirstClass.h
#include <iostream>
#ifndef FIRSTCLASS_H
#define FIRSTCLASS_H
using namespace std;
class FirstClass
{
private:
int *item;
public:
FirstClass();
FirstClass(int thatItem);
~FirstClass();
int getItem();
void setItem(int thatItem);
};
#endif
// the implementation of FirstClass.h
// FirstClass.cpp
#include "FirstClass.h"
using namespace std;
FirstClass::FirstClass()
{
int *setInitial = new int;
*setInitial = 5;
item = setInitial;
}
FirstClass::FirstClass(int thatItem)
{
item = &thatItem;
}
FirstClass::~FirstClass(){}
int FirstClass::getItem()
{
return *item;
}
void FirstClass::setItem(int thatItem)
{
item = &thatItem;
}
// declaration of SecClass
// SecClass.h
#ifndef SECCLASS_H
#define SECCLASS_H
#include "FirstClass.h"
using namespace std;
class SecClass : public FirstClass
{
private:
int *secItem;
public:
SecClass();
SecClass(int newItem, int thatItem);
~SecClass();
int getSecItem();
void setSecItem(int newItem);
};
#endif
// the implementation of SecClass.h
// SecClass.cpp
#include "SecClass.h"
using namespace std;
SecClass::SecClass()
{
int *setSecInitial = new int;
*setSecInitial = 16;
secItem = setSecInitial;
}
SecClass::SecClass(int newItem, int thatItem) : FirstClass(thatItem)
{
secItem = &newItem;
}
SecClass::~SecClass(){}
int SecClass::getSecItem()
{
return *secItem;
}
void SecClass::setSecItem(int newItem)
{
secItem = &newItem;
}
// main program
#include <iostream>
#include "FirstClass.h"
#include "SecClass.h"
using namespace std;
int main()
{
FirstClass classA;
cout << "classA item: " << classA.getItem() << endl << endl;
FirstClass classZ(86);
cout << "classZ item: " << classZ.getItem() << endl << endl;
SecClass classB;
cout << "classB first item: " << classB.getItem() << endl;
cout << "classB second item: " << classB.getSecItem() << endl << endl;
SecClass classC(72, 210);
cout << "classC first item: " << classC.getItem() << endl;
cout << "classC second item: " << classC.getSecItem() << endl;
return 0;
}