I'm probably not the typical beginner here. I am familiar with C, and with OOP in other languages. But I'm having trouble understanding how, in C++, to instantiate an object that may be either of two related classes, one of which is a subclass of the other. (I've hunted around forums and tutorials but have had no success).
I've appended my code below. I've declared BaseClass and SubClass types. In main, I want to create an instance of one or the other, and then call its methods downstream. So I call the appropriate constructor in block (1) or (2), assign it to a pointer to the base class, and then would use it in (3).
The problem is that the instance's deconstructor is invoked as we leave block (1) or (2), so the instance doesn't exist in (3).
I understand why the instance is deconstructed. But I can't for the life of me figure out that right way to do this in C++.
Thanks en avance for any help.
Lamice
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
|
=== main.cpp ===
#include <iostream>
#include "baseclass.h"
#include "subclass.h"
using namespace std;
int main(int argc, char **argv) {
bool useBaseClass = true;
if (argc > 1) useBaseClass = false;
cerr << "about to create an instance" << endl;
BaseClass* instance;
if (useBaseClass) {
// (1)
BaseClass baseInstance(13013);
instance = &baseInstance;
cerr << "base class instance created" << endl;
} else {
// (2)
SubClass subInstance(13013);
instance = &subInstance;
cerr << "sub class instance created" << endl;
}
cerr << "instance created" << endl;
// (3)
// ... do something with the instance ...
}
=== baseclass.h ===
#ifndef BASECLASS_H
#define BASECLASS_H
class BaseClass {
public:
BaseClass(const int items);
virtual ~BaseClass();
// ... other methods here ...
};
#endif
=== baseclass.cpp ===
#include <iostream>
#include "baseclass.h"
using namespace std;
BaseClass::BaseClass(const int items) {
cerr << "in BaseClass::BaseClass" << endl;
// do something with items
}
BaseClass::~BaseClass() {
cerr << "in BaseClass::~BaseClass" << endl;
}
// ... other methods here ...
=== subclass.h ===
#ifndef SUBCLASS_H
#define SUBCLASS_H
class SubClass : public BaseClass {
public:
SubClass(const int items);
~SubClass();
// ... override some of the BaseClass methods here ...
};
#endif
=== subclass.cpp ===
#include <iostream>
#include "baseclass.h"
#include "subclass.h"
using namespace std;
SubClass::SubClass(const int items)
: BaseClass(items) {
cerr << "in SubClass::SubClass" << endl;
}
SubClass::~SubClass() {
cerr << "in SubClass::~SubClass" << endl;
}
// ... override some of the BaseClass methods here ...
|