COCKOS
CONFEDERATED FORUMS
Cockos : REAPER : NINJAM : Forums
Forum Home : Register : FAQ : Members List : Search :
Old 07-06-2017, 10:46 AM   #1
Anomaly
Human being with feelings
 
Anomaly's Avatar
 
Join Date: Sep 2007
Posts: 642
Default Can't access derived class members?

Code:
class A {
public:
  double memberA;
}

class B : public A {
public:
  double memberB
}

B *bclass;
bclass = new B;
bclass->memberB = 1;  <--- ERROR: 'memberB': is not a member of 'A'
I can access public members of base class from outside of class, but not derived class members. I would like to know why?

Thanks
__________________
___________________________
Sonic Anomaly | free JSFX & VST Plugins
Anomaly is offline   Reply With Quote
Old 07-06-2017, 10:49 AM   #2
Xenakios
Human being with feelings
 
Xenakios's Avatar
 
Join Date: Feb 2007
Location: Oulu, Finland
Posts: 8,062
Default

The code as you've written it in your forum post compiles just fine. (After fixing the syntax errors.)

However, if you changed this :

B *bclass;

to this :

A* bclass;

You will get the error you mentioned and it's completely normal and expected. C++ is a statically typed language, so if you have a pointer to class A, you will not be able to access members of class B (directly), even if B derives from A.

What you could do is to cast your pointer :

((B*)bclass)->memberB = 1;

But if you find yourself doing that a lot, your code design probably isn't correct.
__________________
I am no longer part of the REAPER community. Please don't contact me with any REAPER-related issues.

Last edited by Xenakios; 07-06-2017 at 11:03 AM.
Xenakios is offline   Reply With Quote
Old 07-06-2017, 12:11 PM   #3
Anomaly
Human being with feelings
 
Anomaly's Avatar
 
Join Date: Sep 2007
Posts: 642
Default

Quote:
Originally Posted by Xenakios View Post
However, if you changed this :

B *bclass;

to this :

A* bclass;
I feel stupid now! This was the actual problem with my code. I was accidentally pointing to base class instead of derived class. Thanks!
__________________
___________________________
Sonic Anomaly | free JSFX & VST Plugins
Anomaly is offline   Reply With Quote
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT -7. The time now is 09:23 PM.


Powered by vBulletin® Version 3.8.11
Copyright ©2000 - 2024, vBulletin Solutions Inc.