Is there a way to put const and non-const objects in an array?
I am trying to make most of the array elements const to save memory (in Arudino micro controller).
But a few of the array elements can not be const.
The following is one of my failed attempts to polymorph const and non-const elements into an array.
The array of const and non-const objects is on line 40.
#include <iostream>
class Base
{
public:
//overloaded functions
virtualvoid func() = 0; //non-const function
virtualvoid func() const = 0; //const function
};
class ConstN : public Base //class with no variables (just constants)
{
private:
constint n;
public:
ConstN(): n(3) {}
void func() const
{
std::cout << "ConstN::n=" << n << "\n";
}
};
class VarN : public Base //class with variable
{
private:
int n;
public:
VarN(): n(3) {}
void func()
{
std::cout << "VarN::n=" << ++n << "\n";
}
};
int main()
{
const ConstN c; //object is const to save memory (in Arudino micro controller)
VarN v;
Base* ptrBase[] = {&c, &v}; //is there a way to put const and non-const objects in an array?
for (int i=0; i<2; i++)
{
ptrBase[i]->func(); //polymorphism needs func() defined in Base
}
}
it depends sometime if you declare a attribute as mutable.
Note also func() and func() const might be ambiguous at runtime in time that both method are valid in certain cases . So probably a better idea to give different names
Note also that because both methods are pure , you must override them in all derived classes.
#include <iostream>
class Base
{
public:
virtualvoid func() const = 0; //const function
};
class ConstN : public Base
{
private:
constint n;
public:
ConstN(): n(3) {}
void func() const //function is const for n
{
std::cout << "ConstN::n=" << n << "\n";
}
};
class VarN : public Base
{
private:
mutableint n; //mutable
public:
VarN(): n(3) {}
void func() const //function is const to match Base, although n is really mutable
{
std::cout << "VarN::n=" << ++n << "\n";
}
};
int main()
{
const ConstN c;
const VarN v; //mutable const
const Base* ptrBase[] = {&c, &v}; //no way to put const and non-const objects in same array
for (int i=0; i<2; i++)
{
ptrBase[i]->func();
}
}