c++ abstract base class private members
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开发者_如何学Python or is this just wrong?
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
Not all methods in an abstract base class must be pure virtual. You might have some methods which are useful to all subclasses. Thus if you have some functionality in the base class which is modifying internal state you would have private members for those.
If you use the Template Method design pattern (to implement the open/closed principle), it is quite common to have private
members of an abstract base class.
As it stands, your example makes no sense.
However, abstract base classes are allowed to have member function definitions, which in turn are allowed to access private member data in the base class.
You can access Private Members through this shortcut way
Code is in PHP
abstract class myclass1
{
private $var="46789";
public function test($valuetoset)
{
echo $this->var = $valuetoset;
}
}
class myclass2 extends myclass1
{
}
$obj = new myclass2();
$obj->test(78);
精彩评论