Just wanted some clarification. Should abstract base classes never have private members? For example
class abc{
public:
virtual void foo()=0;
private:
int myInt;
}
you can never access myInt since you cannot create an instance of abc and it will not be in a derived class since its private. Is there any situation where you would use private members in abstract base classes or is this just wrong?
If a method of a class is private, you cannot access it outside the current class, not even from the child classes of it. But, incase of an abstract method, you cannot use it from the same class, you need to override it from subclass and use. Therefore, the abstract method cannot be private.
An abstract method cannot be private as in the following, abstract class Demo() { private abstract void Call();
An abstract class must provide implementation for all interface members.
An abstract class is a class that is designed to be specifically used as a base class. An abstract class contains at least one pure virtual function. You declare a pure virtual function by using a pure specifier ( = 0 ) in the declaration of a virtual member function in the class declaration.
In C++ you can have an abstract class that has non pure virtual methods. In that case, and depending on the design it can make sense to have private members:
class base {
std::string name;
public:
base( std::string const & n ) : name(n) {}
std::string const & getName() const { return name; }
virtual void foo() = 0;
};
That code ensures that every object that derives from base has a name, that is set during construction and never changes during the lifetime of the object.
EDIT: For completion after Charles Bailey reminded me of it in his answer
You can also define pure-virtual functions, and in that case, private attributes could also make sense:
// with the above definition of base
void base::foo() {
std::cout << "My name is " << name << std::endl;
}
It's normally not advisable to have data members in an abstract class but there is nothing technically wrong with your example. In the implementation of foo
, which is publicly accessible you can use myInt
for whatever purposes you like.
For example:
class abc{
public:
virtual void foo()=0;
private:
int myInt;
};
class xyz : public abc
{
virtual void foo();
};
#include <iostream>
#include <ostream>
void xyz::foo()
{
std::cout << "xyz::foo()\n";
abc::foo();
}
void abc::foo()
{
std::cout << "abc::foo(): " << myInt++ << '\n';
}
#include <memory>
int main()
{
std::auto_ptr<abc> p( new xyz() ); // value-initialization important
p->foo();
p->foo();
}
Output:
xyz::foo()
abc::foo(): 0
xyz::foo()
abc::foo(): 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With