[ACCEPTED]-c++ abstract base class private members-base
In C++ you can have an abstract class that 10 has non pure virtual methods. In that case, and 9 depending on the design it can make sense 8 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 7 that every object that derives from base 6 has a name, that is set during construction 5 and never changes during the lifetime of 4 the object.
EDIT: For completion after Charles 3 Bailey reminded me of it in his answer
You can 2 also define pure-virtual functions, and in that case, private 1 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 5 members in an abstract class but there is 4 nothing technically wrong with your example. In 3 the implementation of foo
, which is publicly 2 accessible you can use myInt
for whatever purposes 1 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
Not all methods in an abstract base class 5 must be pure virtual. You might have some 4 methods which are useful to all subclasses. Thus 3 if you have some functionality in the base 2 class which is modifying internal state 1 you would have private members for those.
If you use the Template Method design pattern (to implement the open/closed principle), it 2 is quite common to have private
members of an abstract 1 base class.
As it stands, your example makes no sense.
However, abstract 4 base classes are allowed to have member 3 function definitions, which in turn are 2 allowed to access private member data in 1 the base class.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.