Ricardo Alves
Ricardo Alves

Reputation: 1121

C++ Extending Class Forcing some methods private

My question is simple: ~Given two classes, I want to one of them to extend the other one, but turning some methods to be private:

Class B
public Method a();
public Method b();
public Method c();

Class A extends B
private Method a();
private Method b();
public Method c();

Is this possible and how? Thanks!

Upvotes: 0

Views: 420

Answers (3)

KalyanS
KalyanS

Reputation: 527

You could change the inheritance type from public to private, when you declare class B.

class B : public A {
   private:
      baseMethod();
};
or
class B : private A {
   public:
      baseMethod();
};

The use appropriate override that you want for each method.

Looks like you don't want all of the methods to turn private. Choose the type of inheritance based on the fraction of methods changing their visibility.

Upvotes: 0

abelenky
abelenky

Reputation: 64682

This is what Private Inheritance is for.

class A:   private B
{
    // All methods of class B are now private.
    // To make some "public" again:
    public:
        Method c()  { return B::c(); } // Call the private c-method from class B.
};

Upvotes: 1

Matt
Matt

Reputation: 6050

Use private inheritance, all the function in base class B will become private.

  class A:   private B
  {
  }

Difference between private, public, and protected inheritance in C++ are explained here.

Upvotes: 1

Related Questions