Note that there are some explanatory texts on larger screens.

plurals
  1. POshould base class have attributes?
    primarykey
    data
    text
    <p>In another community, i have people suggesting that you should 'NEVER' have attributes in your base class. Instead it should have only pure virtual functions and let the derived class take responsibility to provide definition for all these methods.</p> <p>My take on it is that 'It is not a rule of thumb'. I gave following trivial example:</p> <pre><code>class Shape { protected: double Area; double Perimeter ; public: Shape():Area(0.0), Perimeter(0.0){} double getArea(){return Area;} double getPerimeter (){return Perimeter;} virtual void setArea () = 0 ; virtual void setPerimeter () = 0 ; }; class Rectangle : public Shape { private : double length ; double breadth ; public: Rectangle ():length(0.0),breadth(0.0){} Rectangle (int _length, int _breadth):length(_length),breadth(_breadth){} void setArea () { Area = length * breadth ; } void setPerimeter () { Perimeter = 2 * (length + breadth) ; } } ; </code></pre> <p>With the example given above, i feel that any shape has following attributes <strong>'Area'</strong> and <strong>'Perimeter'</strong> and hence if we do not provide these attributes in the class, the <strong>Shape class</strong> would not be a appropriate representation of <strong>'Real world shape'</strong></p> <p>Please let me know your opinion on this.</p> <p><strong>EDIT:</strong></p> <p>The first thing which i would say is indeed my code is a naive one and doesn't make much sense w.r.t. the design. I thought earlier that i would add a line saying that this was just an example and the whole point of this post is to know if 'Base class should <strong>NEVER</strong> have attributes'. But then i thought that i'll get some good design suggestions too and i indeed have got many :)</p> <p>Coming to the question, with all the posts below, i understand that its not a rule of thumb and it is design choice (which is exactly i wanted to emphasize). Having said that i also acknowledge that it would be desirable to NOT have attributes in the base class if these attributes can be calculated (or derived) as Area = Length * Breadth. Thanks a lot for all your answers (i wish i had option to accept more than one answer).</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload