Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is inherited member not allowed?

I'm beginner to C++ and I'm doing one of the exercises about abstract class and inheritance.

This is my abstract class:

#ifndef   SHAPE_H  #define  SHAPE_H class Shape {     public:         virtual void area();         virtual void perimeter();         virtual void volume(); }; #endif 

This is my concrete class that implements the abstract class:

#include <iostream> #include <cmath> #include "Shape.h" using namespace std;  class Circle : public Shape {     public:         Circle(int);     private:         int r; };  Circle::Circle(int rad) {     r = rad; }  void Circle::area() {     cout << "Area of this cirle = " << 3.14 * pow(r, 2) << endl; }  void Circle::perimeter() {     cout << "Perimeter of this cirle = " << 2 * 3.14 * r << endl; }  void Circle::volume() {     cout << "Volume is not defined for circle." << endl; } 

I got red lines under area(), perimeter(), and volume() in my Circle class, which showed "Error: inherited member is not allowed". I went through my class ppt and googled for answer but no luck. Any help is appreciated.

like image 363
user1447343 Avatar asked Feb 27 '13 16:02

user1447343


People also ask

Which member function Cannot be inherited?

Constructor cannot be inherited but a derived class can call the constructor of the base class.

Can data members be inherited?

Only the protected members can be inherited but remain private to class. If static members are defined in private access, they won't be allowed for inheritance.

How can private members access inheritance?

Private members of a base class can only be accessed by base member functions (not derived classes). So you have no rights not even a chance to do so :) Show activity on this post. Well, if you have access to base class, you can declare class B as friend class.


2 Answers

You have to declare the over-ridden functions as part of your class definition

class Circle : public Shape     {     public:         Circle(int);         virtual void area(); // overrides Shape::area         void perimeter();    // overrides Shape::perimeter         virtual void volume();     private:         int r;     }; 

Note that the use of virtual here is optional.

As n.m. noted, you should also include a virtual destructor in Shape. You may also want to make its virtual functions pure virtual (based on your comment about Shape being abstract)

class Shape { public:     virtual ~Shape() {}     virtual void area() = 0;     virtual void perimeter() = 0;     virtual void volume() = 0; }; 
like image 58
simonc Avatar answered Sep 23 '22 21:09

simonc


you have to declare the override methods too in the Circle class

class Circle : public Shape     {     public:         Circle(int);         virtual void area();         virtual void perimeter();         virtual void volume();     private:         int r;     }; 
like image 34
V-X Avatar answered Sep 21 '22 21:09

V-X