What is the purpose of using public fields in abstract classes?

Why not put all members under protected and private only?

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Shape
{
public:
void draw() const;
virtual void move(int dx, int dy);

void set_color(Color col);
Color color() const;

//etc...

protected:
Shape(){};
Shape(initializer_list<Point> lst);

//etc...

private:
//etc...
};


If the constructor is unable to be called unless by a derived class, why are there any public functions at all?

A general explanation of the uses and non-obvious purposes of abstract classes would be helpful if anyone is inclined to do so.
Last edited on
why are there any public functions at all?


The abstract base provides the interface for interacting with derived classes. If there are no methods one can use through a pointer or reference to the interface, it kind of misses the point.

For instance, if we have:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <memory>
#include <vector>

class Shape
{
    virtual void draw() const = 0;
    virtual ~Shape() {}
};

class Rectangle : public Shape
{
public:
    void draw() const { std::cout << "Rectangle::draw\n"; }
};

class Circle : public Shape
{
public:
    void draw() const { std::cout << "Circle::draw\n"; }
};

int main()
{
    std::vector<std::unique_ptr<Shape>> shapes = { std::make_unique<Rectangle>(), std::make_unique<Circle>() };

    for (auto& shape : shapes)
        shape->draw();
}


The code won't compile because Shape::draw is inaccessible.
It won't compile because draw() is private. In my example I was asking why draw() was public instead of protected, since Shape itself could not call draw().
Hi,

In your OP, it looks like the constructors were made protected so that an object could not be instantiated from the Shape class. This is an alternative way of achieving the same effect as being abstract, but they have only done this because there were no pure virtual functions.

But all those public functions should be pure virtual, because they form the public interface, non derived classes might need to call them. And derived classes probably need to redefine them.

It is possible to have a protected interface, but this isn't a good situation for that, as I just explained.

Good Luck !!
It won't compile because draw() is private. In my example I was asking why draw() was public instead of protected, since Shape itself could not call draw().


Whether draw is private or protected, the result is the same. draw would not be accessible and the code would not compile.
Topic archived. No new replies allowed.