abstract class and virtual function
-
Dear all,
in a header file I've defined an abstract class (SegmentGroup) and a concrete class (Sgz) dirived from the former:class SegmentGroup { protected: QVector<QString> segments; public: void appendSegment(QString); virtual void assignSegment() = 0; virtual QVector<QString> getSegments() = 0; }; class Sgz : public SegmentGroup { public: Segment cnt; Segment unt; };
In the corresponding source file I've following definition:
void SegmentGroup::appendSegment(QString str) { segments.append(str); } void Sgz::assignSegment() { foreach (QString seg, segments) { if (seg.startsWith("CNT+")) cnt.segStr = seg; else if (seg.startsWith("UNT+")) unt.segStr = seg; } } QVector<QString> Sgz::getSegments() { QVector<QString> segment; if (!cnt.segStr.isEmpty()) segment.append(cnt.segStr); if (!unt.segStr.isEmpty()) segment.append(unt.segStr); return segment; }
In my main() function I've declared an object of Sgz. But the compiler tells me that I cannot define an object of an abstract class. I think that I've made Sgz a concrete class by defining the both virtual functions in the base class. What's the error? Thanks for any hint!
Weichao[koahnig: code tags added]
-
@Weichao-Wang said in abstract class and virtual function:
But the compiler tells me that I cannot define an object of an abstract class.
Please post the exact error. Also you're missing the functions' declarations in
Sgz
. -
That would look better:
class SegmentGroup { protected: QVector<QString> segments; public: void appendSegment(QString); virtual void assignSegment() = 0; virtual QVector<QString> getSegments() = 0; }; class Sgz : public SegmentGroup { public: void assignSegment(); // redeclaration required QVector<QString> getSegments(); // redeclaration required Segment cnt; Segment unt; };
Note: at least that was the syntax some standards ago. In case that became obsolete, I appreciate the hint. I was simply too lazy to check ;)
-
@kshegunov
Now I understand that you mean the same as koahnig. Thank you!
Weichao -
Please mark püost as solved then
-
South of Germany resp south of Lake Constance (Bodensee)
-
Hi,
With C++11, you can add the
override
keyword after the declaration of each function you re-implement. This will give the compiler a hint that will allow him to scream at you if you try to re-implement a non virtual function.