trying to make a class (ABase) non-derivable

A

Amit

please see the following lines of codes :

class ABase; // i want to make it non-derivable

class Super
{
private:
Super () {};
friend class ABase;
};

class ABase : virtual public Super
{
private:
int i;
public:
ABase () {}
void seti (int j) { i=j; }
int geti () { return i; }
};

void main()
{
ABase a;
a.seti(100);
cout<<endl<<a.geti()<<endl;
}

here if we try to derive a class from ABase ;
class BDer : public ABase
{
public:
BDer() {}
};

the compiler is giving an error "Super::Super' : cannot access private
member declared in class 'Super'".

But if we remove the "virtual" in class ABase : virtual public Super,
then we can derive from ABase. How the keyword "virtual" making ABase
non-derivable??? Is there any workaround for this problem???

I hope the problem is clear to you.

Thanks,
Amit Kumar.
 
V

Victor Bazarov

Amit said:
please see the following lines of codes :

class ABase; // i want to make it non-derivable
[..]

This is a FAQ. Please look in the archives.
 
J

Jonathan Mcdougall

please see the following lines of codes :
class ABase; // i want to make it non-derivable

See FAQ[23.8]
class Super
{
private:
Super () {};
friend class ABase;

};
class ABase : virtual public Super
{
private:
int i;
public:
ABase () {}
};
void main()

See FAQ[29.3]
{
ABase a;
a.seti(100);
cout<<endl<<a.geti()<<endl;
}
here if we try to derive a class from ABase ;
class BDer : public ABase
{
public:
BDer() {}
};
the compiler is giving an error "Super::Super' : cannot access private
member declared in class 'Super'".
But if we remove the "virtual" in class ABase : virtual public Super,
then we can derive from ABase. How the keyword "virtual" making ABase
non-derivable???

See FAQ[25.12]
Is there any workaround for this problem???

See FAQ[23.8] again.
I hope the problem is clear to you.

Yes. RTFM.

Jonathan
 
Joined
Oct 10, 2008
Messages
3
Reaction score
0
Generic solution for non-derivable classes in C++

Well, making a class non-derivable is really simple. You can find the answer in FAQ. However, having a generic solution for this problem is better, but harder to implement. I was investigating this problem a long time ago. Basically, a mix of template friends, access levels and virtual inheritance does this job. The article about my solution can be found here - http://www.jetsnail.com/tech-blog/38-cpp/52-noninheritable. I hope you will like it! :tea:
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top