a derived class inherits all members of the base class, that is what the book says, right? i want to make a derived class that has only some of the members of the base class, and some of its own members and functions, is it ok to do it like this? or shall i get error msgs. i dont like error msgs at all !

nemo

Dani AI

Generated

Good, simple tip from . A few practical additions that are useful on exams and in real code when a derived type should present only part of a base's functionality.

Composition (preferred): embed the base as a member and forward only the operations meant to be exposed. This gives full control over the visible API and avoids accidental "is-a" semantics.

class Base {
public:
  void allowed();
  void hidden();
};

class Thin {
  Base b_;               // composition
public:
  void allowed() { b_.allowed(); }   // expose only this
};

Disable or hide inherited functions: declare the same signature in the derived type and mark it = delete to make calls on derived objects ill-formed. Note the caveat: calls through a Base pointer or reference still resolve according to the usual dispatch rules.

struct Base { void f(); };
struct Derived : Base {
  void f() = delete;     // calls on Derived objects are rejected
};

Adjust accessibility or selectively re-expose members: a using-declaration inside Derived can bring a base member into a different access section (it cannot expose base private members). Name hiding and overload resolution rules matter here, so be mindful when you add new overloads in the derived class.

For guidelines and language details see cppreference on inheritance, using-declarations, and deleted functions. When the goal is a reduced interface rather than a true subtype relationship, prefer composition; reserve inheritance for genuine "is-a" cases and understand the runtime/overload implications before hiding or deleting members.

References: , cppreference — using-declaration, , C++ Core Guidelines

Recommended Answers

All 2 Replies

you can't. Like the book says, derived class inherits ALL members of the base class. But, what you can do is make members of the base class not accessible to members of derived class by making base class members private. In the code below, class derived cannot access variable x in class base.

class base
{
...
private:
   int x;
}

class derived : public base
{
...
};

hey thanks , simple solution!! i tried another way and it worked too, but i'll remember ur simple tip in future ( my exam is pretty close.
regards,

nemo

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.