I have this code, but I don’t see where I went wrong here. It seem to compile OK but I cannot access Computer or Appliance functions. Can someone please help me understand how can I make an array that holds different objects on this code example I have here?
#include <iostream>
using namespace std;
class Technics
{
private:
int price, warranty;
static int objCount;
double pvn;
char *name, *manufacturer;
public:
Technics()
{
this->objCount++;
};
Technics(int price)
{
this->objCount++;
this->price = price;
}
~Technics(){
this->objCount = this->objCount - 2;
};
static int getObjCount()
{
return objCount;
}
void setPrice(int price)
{
this->price = price;
}
int getPrice()
{
return this->price;
}
void resetCount()
{
this->objCount = 0;
}
};
int Technics::objCount = 0;
class Computer : public Technics
{
private:
int cpu, ram, psu, hdd;
public:
Computer() {}
Computer(int price)
{
this->setPrice(price);
}
void setCpu(int cpu)
{
this->cpu = cpu;
}
int getCpu()
{
return this->cpu;
}
};
class Appliance : public Technics
{
private:
int height;
int width;
char* color;
char* type;
public:
Appliance(){}
Appliance(int height, int width)
{
this->height = height;
this->width = width;
}
void setWidth(int width)
{
this->width = width;
}
int getWidth()
{
return this->width;
}
};
void main()
{
//Creating array
Technics *_t[100];
// Adding some objects
_t[0] = new Computer();
_t[1] = new Computer();
_t[2] = new Appliance();
// I can access only properties of Technics, not Computer or Appliance
_t[0]->
int x;
cin >> x;
}
The line:
Creates a computer object and stores it as a Technics base pointer in the array (i.e. for all intents and purposes while in that array, it is a Technics object).
You need to cast back to the derived class to access members that are more derived than those in Technics:
Use dyncamic cast if you don’t know which derived type it is – it will return the casted pointer on success and NULL on fail so it’s kind of a type-check – it has big runtime overhead though, so try to avoid it 🙂
EDIT in response to your closing comment:
PS: you could also use std::vector which is dynamically changeable as opposed to just created at run time – it’s the best option if your allowed to use it. It saves you making your own resizable array code. Google it 😉