473,851 Members | 2,236 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Un-ringing the bell: making parent methods unavailable to children

Is it possible to make a public parent class method unavailable (i.e.,
generate an error at compile time) to a particular child class?

For example, say a parent class has a public method Add( ). I want to create
a child class of this parent class that does not have an Add( ) method
(while possibly another child class does).

I think I figured it out while writing this, so tell me if this is the
'standard method'. Make the parent class public method virtual, and then
polymorph it in the child class as private. That is:

class Parent_Class
{
public:
Add( ) { // do something // }
} ;

class Child_Class : public Parent_Class
{
private:
Add( ) {} // now child instance can't call Add( ) publically
} ;

[==Peteroid==]
Nov 17 '05 #1
3 1192
This doesn't work. See below.

class Parent_Class
{
public:
void Add( ) {/* do something */};
} ;

class Child_Class : public Parent_Class
{
private:
void Add( ) {}; // now child instance can't call Add( ) publicly
} ;

int main()
{
Child_Class ck;
((Parent_Class* )&ck)->Add();
}

Ronald Laeremans
Visual C++ team
"Peteroid" <pe************ @msn.com> wrote in message
news:%2******** ********@TK2MSF TNGP14.phx.gbl. ..
Is it possible to make a public parent class method unavailable (i.e.,
generate an error at compile time) to a particular child class?

For example, say a parent class has a public method Add( ). I want to
create
a child class of this parent class that does not have an Add( ) method
(while possibly another child class does).

I think I figured it out while writing this, so tell me if this is the
'standard method'. Make the parent class public method virtual, and then
polymorph it in the child class as private. That is:

class Parent_Class
{
public:
Add( ) { // do something // }
} ;

class Child_Class : public Parent_Class
{
private:
Add( ) {} // now child instance can't call Add( ) publically
} ;

[==Peteroid==]

Nov 17 '05 #2
I see your point, but it does require going out of your way by virtue of
'tricking' the compiler into treating it as an instance of its parent (i.e.,
you have to know you are doing it purposefully, you can't 'accidentally' use
Add() from an instance of the child class). I tend to avoid pointers and
typecasting in my code anyway, they can get you into this kind of trouble
(i.e., shoot yourself in the foot by forcing the compiler to treat a pointer
to one type of data structure as a pointer to another type via overriding
typecasts)...

So, based on your example, technically a child instance still can't use
Add() unless it is type case as its parent class. And even then, won't the
virtual function table still use the child's version of Add() via
polymorphism? If not, the trick you mentioned would also override
polymorphism in general. Note that in any case that Add() is polymorphed
into a NOP for safety, and I could put an 'assert(false) inside it to make
sure it told me at run time if it ever tried to use it (as a last ditch
protection, having failed discovering problem at compile time) .

Do you have a better way of making a parent public method unavailable to a
child instance? Love to hear it... :)

[==Peteroid==]
"Ronald Laeremans [MSFT]" <ro*****@online .microsoft.com> wrote in message
news:%2******** ********@TK2MSF TNGP09.phx.gbl. ..
This doesn't work. See below.

class Parent_Class
{
public:
void Add( ) {/* do something */};
} ;

class Child_Class : public Parent_Class
{
private:
void Add( ) {}; // now child instance can't call Add( ) publicly
} ;

int main()
{
Child_Class ck;
((Parent_Class* )&ck)->Add();
}

Ronald Laeremans
Visual C++ team
"Peteroid" <pe************ @msn.com> wrote in message
news:%2******** ********@TK2MSF TNGP14.phx.gbl. ..
Is it possible to make a public parent class method unavailable (i.e.,
generate an error at compile time) to a particular child class?

For example, say a parent class has a public method Add( ). I want to
create
a child class of this parent class that does not have an Add( ) method
(while possibly another child class does).

I think I figured it out while writing this, so tell me if this is the
'standard method'. Make the parent class public method virtual, and then
polymorph it in the child class as private. That is:

class Parent_Class
{
public:
Add( ) { // do something // }
} ;

class Child_Class : public Parent_Class
{
private:
Add( ) {} // now child instance can't call Add( ) publically
} ;

[==Peteroid==]


Nov 17 '05 #3
Your example did not have the method as virtual.

My assumption was that you were asking for a method that would make it
impossible for an instance of a derived class to call it, not just less
convenient. And the former cannot be done by any method I can think of. Of
course making the method private in the derived class will prevent it from
being called directly.

Thanks.

Ronald

"Peteroid" <pe************ @msn.com> wrote in message
news:ub******** ******@TK2MSFTN GP10.phx.gbl...
I see your point, but it does require going out of your way by virtue of
'tricking' the compiler into treating it as an instance of its parent
(i.e.,
you have to know you are doing it purposefully, you can't 'accidentally'
use
Add() from an instance of the child class). I tend to avoid pointers and
typecasting in my code anyway, they can get you into this kind of trouble
(i.e., shoot yourself in the foot by forcing the compiler to treat a
pointer
to one type of data structure as a pointer to another type via overriding
typecasts)...

So, based on your example, technically a child instance still can't use
Add() unless it is type case as its parent class. And even then, won't the
virtual function table still use the child's version of Add() via
polymorphism? If not, the trick you mentioned would also override
polymorphism in general. Note that in any case that Add() is polymorphed
into a NOP for safety, and I could put an 'assert(false) inside it to make
sure it told me at run time if it ever tried to use it (as a last ditch
protection, having failed discovering problem at compile time) .

Do you have a better way of making a parent public method unavailable to a
child instance? Love to hear it... :)

[==Peteroid==]
"Ronald Laeremans [MSFT]" <ro*****@online .microsoft.com> wrote in message
news:%2******** ********@TK2MSF TNGP09.phx.gbl. ..
This doesn't work. See below.

class Parent_Class
{
public:
void Add( ) {/* do something */};
} ;

class Child_Class : public Parent_Class
{
private:
void Add( ) {}; // now child instance can't call Add( ) publicly
} ;

int main()
{
Child_Class ck;
((Parent_Class* )&ck)->Add();
}

Ronald Laeremans
Visual C++ team
"Peteroid" <pe************ @msn.com> wrote in message
news:%2******** ********@TK2MSF TNGP14.phx.gbl. ..
> Is it possible to make a public parent class method unavailable (i.e.,
> generate an error at compile time) to a particular child class?
>
> For example, say a parent class has a public method Add( ). I want to
> create
> a child class of this parent class that does not have an Add( ) method
> (while possibly another child class does).
>
> I think I figured it out while writing this, so tell me if this is the
> 'standard method'. Make the parent class public method virtual, and
> then
> polymorph it in the child class as private. That is:
>
> class Parent_Class
> {
> public:
> Add( ) { // do something // }
> } ;
>
> class Child_Class : public Parent_Class
> {
> private:
> Add( ) {} // now child instance can't call Add( ) publically
> } ;
>
> [==Peteroid==]
>
>



Nov 17 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
6300
by: Agathe | last post by:
Bonjour, Je souhaite insérer dans une table MySQL des données provenant d'un fichier texte grâce à un script PHP. Mon fichier porte l'extension "txt" et les données sont séparées par des ";'. J'ai créé un script qui upload le fichier texte sur le serveur et qui lit le contenu de chaque ligne, sépare chaque champ, puis stocke les données dans un tableau indicé pour ensuite insérer ces données dans une table MySQL. Mon script fonctionne...
6
5382
by: Raymond H. | last post by:
Bonjour, Je n'arrive pas à savoir comment lire via vb4 l'adresse d'un favoris dans le dossier des favoris où Internet Explorer place ses favoris. Par exemple, comment fait-on pour afficher l'url d'un favoris dans un msgbox? Raymond H. logicipc@sympatico.ca
2
4928
by: Mauro | last post by:
Ciao a tutti! vorrei sapere se qualcuno potrebbe darmi qualche dritta (o se sa dove reperire un tutorial) su come realizzare un trial a tempo, da integrare ad un mio programma per impedirne l'utilizzo allo scadere di un dato periodo (ad esempio 30 giorni) o come implementare l'algoritmo per il controllo della chiave di sblocco. Grazie anticipatamente per l'aiuto. Ciao, Mauro.
1
2161
by: richard | last post by:
bonjour je me connecte à une base de données interbase/firebird en utilisant, KinterbasDB http://kinterbasdb.sourceforge.net/ pour ceux que ca interesse mais je pense que le probleme est le meme quel que soit la bdd j'aimerais acceder a un champs par sont nom plutot que par son index dans le record en cours, comme je fais maintenent
3
3906
by: pascal Joseph | last post by:
J'ai un formulaire avec un seul champ text appelé "unite" et un bouton. En javascript j'aimerai utiliser un script qui interdise les valeurs de type "char" et soit supérieur à 0 J'ai trouvé ce code mais je ne sais pas comment l'appliquer, fonctionne-t-il? <script>
5
1982
by: Chris | last post by:
Bonjour, Plusieurs fichiers PHP d'un programme open source de compteur de visites viennent de se faire hacker sur mon serveur (hébergement mutualisé chez un fournisseur d'accès). Le hacker a déposé un code permettant visiblement de passer un script en argument tout en signant son passage (rory). Je voulais savoir quel était la meilleure façon de sécuriser ces fichiers. Comme c'est un serveur Unix, j'ai déjà corrigé les autorisations...
3
16134
by: Jorge Gallardo | last post by:
Hola de nuevo a todos... Agradecido a todos los que me habeis solucionado problemas anteriores... Pero como no es novedad, me surge otro. Recientemente buscando, adquiri un codigo para juntar 3 ficheros de texto. El cual adapte para el desarrollo de mi DB. El proceso es genial, pues junto los tres ficheros pulsando solo un boton. (O determinada accion EVENTOS)
1
3385
by: Alex | last post by:
Ciao a tutti, sto sviluppando un applicazione windows, in breve all'interno dello stesso namespace ho un form con una datagrid e un thread che effettua dei controlli e "dovrebbe" caricare i dati sulla datagrid stessa. - nel namespace ho dichiarato un riferimento al form in questo modo: private static Form1 f; - nel form load istanzo e lancio il thread, nel thread eseguo i
15
1907
by: Ciudad Tecnópolis | last post by:
Hola, primero que todo mil disculpas por postear una pregunta no relacionada al tema pero se que será muy útil para todos! Actualmente estoy presentando un desarrollo en .NET para una compañía y unos tipejos me están echando el negocio al suelo pues hablan pestes de .NET y le dicen al director de sistemas de la compañía que Linux y PHP son lo máximo!!! , por favor alguien tiene textos o material de cualquier tipo.. videos ....
3
2908
by: nano9 | last post by:
Hola gente quisiera que alguien me pudiera ayudar con un problemilla que tengo, resulta que estoy programando en ASP con C# y estoy usando un cadbgrid que se comporta parecido a un datagrid o dbgrid pero tiene otras peculiaridades ahi que facilitan muchas tareas. Si alguno ha usado este control talvez me podria ayudar. El asunto esta asi, estoy queriendo agregar un mensaje en una etiqueta debajo del grid para indicar la cantidad de items...
0
9748
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11020
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10670
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10735
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10356
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9506
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7907
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5934
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3180
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.