Calling a pure virtual
function in another member function shouldn't be a problem at all. (Unfortunately, OP didn't copy/paste the exact error message.)
The exposed sample of OP has unfortunately a lot of typos, syntax errors, and other weaknesses.
Fixing this, I found one essential issue: the const
-ness of Parent::getFunc()
.
Parent::getFunc()
calls a non-const member function and mutates the member variable this->var
which is not accepted by the compiler.
Removing the const
, it worked.
Fixed sample:
#include <iostream>
#include <string>
class Parent{
public:
Parent() = default;
virtual std::string func() = 0; // PURE VIRTUAL
std::string getFunc() // WRONG: const
{
return var = func();
}
protected:
std::string var;
};
class Child: public Parent {
public:
Child() = default;
virtual std::string func() override
{
std::string random; // this is very generic I actually pretend
//to do some math here and return a string
return random;
}
};
#define DEBUG(...) std::cout << #__VA_ARGS__ << ";\n"; __VA_ARGS__
int main()
{
DEBUG(Child child);
DEBUG(child.getFunc());
}
Output:
Child child;
child.getFunc();
Live Demo on coliru
Though, a const
accessor (I would call it “getter”) seems reasonable. With a little bit more re-design, it can be achieved as well:
#include <iostream>
#include <string>
class Parent{
public:
Parent() = default;
virtual std::string func() const = 0; // PURE VIRTUAL
std::string getFunc() const
{
return var = func();
}
protected:
mutable std::string var;
};
class Child: public Parent {
public:
Child() = default;
virtual std::string func() const override
{
std::string random; // this is very generic I actually pretend
//to do some math here and return a string
return random;
}
};
#define DEBUG(...) std::cout << #__VA_ARGS__ << ";\n"; __VA_ARGS__
int main()
{
DEBUG(Child child);
DEBUG(child.getFunc());
}
Output: the same like above
Live Demo on coliru
Note:
I made the virtual func()
const
to make it accessable for const
instances / member functions.
The member variable became mutable
to make it writable in const
member functions.
I must admit that I personally find the mutable
a bit scaring. In my simple mind, something is const
or it isn't. However, the mutable
just seems to be invented for update of internal caching of actually const
objects. So, it might be the right tool here. (It's a little bit hard to say without more context.)
More about mutable
: mutable specifier