473,608 Members | 2,264 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 1176
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
6277
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
5366
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
4911
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
2146
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
3887
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
1966
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
16059
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
3363
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
1877
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
2890
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
8002
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
8496
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
8475
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...
0
6816
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
6013
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
3962
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4024
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2474
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1329
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.