Sign in to follow this  

Access private base members from derived

This topic is 4666 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Is possible to access private data member of a Base class from a derived class in C++? For example:
class Base { 
private: int i;
};

class Derived : public /* private or protected */ Base {
public:
void func(int n) { i = n; }
};


I get this error compiling it in MSVC 6.0: main.cpp(49) : error C2248: 'i' : cannot access private member declared in class 'Base' see declaration of 'i' Thanks

Share this post


Link to post
Share on other sites
Making data members with protected access is most often "the sin of satan" and very contradictive, generally a sign of bad design unless there is real rationale for there use and there truely is such a tight coupling between parent & child types, in most case there isn't so don't fall into bad habbits.

Share this post


Link to post
Share on other sites
Quote:
Original post by snk_kid
Making data members with protected access is most often "the sin of satan" and very contradictive, generally a sign of bad design unless there is real rationale for there use and there truely is such a tight coupling between parent & child types, in most case there isn't so don't fall into bad habbits.


Care to explain in more detail? I don't understand why derived classes shouldn't have access to their base class's member variables.

Share this post


Link to post
Share on other sites
Encapsulation. The variables are private members of that class, and even though another class is derived from that base, it's still a different class. Private specifies access to only members of that base class. Protected specifies access to derived classes and friend functions. What some, like I at the moment, do is to just use the access functions to get to those variables. The data stays locked away and only the base class and its original functions can directly access that data.

I'm sure someone better at this can explain it more easily than I can.

Share this post


Link to post
Share on other sites
generally, it's a sign of bad design. Usually, the variables should be accessed through the members the base class provides.

Also, you can access the base class's private fields (Note: this is a sign of even worse design) if you make it a friend, like this(it's been a while since I've used friends, so this may be a little off):

class BaseClass {
private:
int x;
};

class DerivedClass : public BaseClass {
friend BaseClass;
};

Remember: You should probably never use this, as it's usually bad design, just FYI.

Share this post


Link to post
Share on other sites
Quote:
Original post by MobileOak
Quote:
Original post by snk_kid
Making data members with protected access is most often "the sin of satan" and very contradictive, generally a sign of bad design unless there is real rationale for there use and there truely is such a tight coupling between parent & child types, in most case there isn't so don't fall into bad habbits.


Care to explain in more detail? I don't understand why derived classes shouldn't have access to their base class's member variables.


Because it's an implementation detail that doesn't need to be known, it should be pretty obvious why its called an abstraction, i even high-lighted the main terms coupling and also to enforce state invariants, polymorphic types and type inheritance in general is mainly about extending behaviours/operations not extending implementation, i'm not saying never, i'm say in most cases its abused without any rationale it may aswell be public. I'm not gonna go into any more details, just google it and you will get millions of hits about it.

In theory public virtual member functions considered are bad aswell but that is beyond the scope of this if you want to know more then google up on non-virtual interface idiom.

Share this post


Link to post
Share on other sites
Here is a hack that lets you use private members in a derived class.


class base{
private:
int i;
};

class derived : public base
{
private:
using base::i;
};



Though that is so ugly I shouldn't have even mentioned it.

Share this post


Link to post
Share on other sites
Quote:
Original post by Jingo
Here is a hack that lets you use private members in a derived class.

*** Source Snippet Removed ***

Though that is so ugly I shouldn't have even mentioned it.


WHAT THE HECK [lol] I'll have to give that a try [smile]

Share this post


Link to post
Share on other sites
ive heard snk_kid say this before, but i still do not understand why this is. lets say we have a class called "Animal", which represents an animal in a game. we also wanted cats and dogs in the game, too, so we made them as well. so the classes would look like this:


class Animal
{
public:

Animal();
~Animal(){};

protected:

float x,y,z;
};

class Dog : public Animal
{
public:
void Wag_Tail();
};

class Cat : public Animal
{
public:
void Chase_Mouse();
};



now, cats and dogs have a position, but different behaviors. if i made x,y,z as private, wouldnt this mean i would have to cut and paste "float x,y,z" into the Dog and Cat classes? actually, now i cant remember if they do inherit the data, but they just cannot touch it. either way though, how would you handle this then?

Share this post


Link to post
Share on other sites
dont listen to the guy too much. If you have protected data you arnt necsesarily doing anything wrong.

for example i have a world
my world contains objects
to be in the world the objects must have a position

therefore if an object doesnt have a position he will not work in the world

so to force all objects to have a position so they work with the world i will force them to derive from a base entity class that has a protected var position

what did i acomplish
I guaranteed that my objects will work in the world
I didnt have to make 3 floats everytime i made a new object

so my code will be more bug free and i will write it faster

if you have some protected data that you derived and have no use for it then say UH OH i might have a bad design here otherwise use protected if you want

Share this post


Link to post
Share on other sites
If you have position in the base class, as you do, then the base class should surely provide an interface with which to act on the position values, the derived class can then be implemented in terms of this interface.

Share this post


Link to post
Share on other sites

your are talking about doing this, not to use protected members ?

class Base {
private:
int data;
public:
void SetData(int);
int GetData() const;
};

class Derived : public Base {
private:
public:
void func(int n) { SetData(n); }
};

Share this post


Link to post
Share on other sites
ok dude. trying to avoid using protected data will eventually be like making get set accessors for everything because you are trying to be "Object Oriented".

an example of the most retarded code ive ever seen

class Point
{
GetX() { return x; }
GetY() { return y; }
SetX(int X) { x = X; }
SetY(int Y) { y = Y; }

private:
int x;
int y;
};

As far as i can tell what you saying is by the time you get around to deriving the base class their should be functions to act on the data so you can avoid doing it yourself. When shit is simple its simple. a Point class is a good example. theirs no reason for that class its just a waste of typing. You guys make good points but the original poster is obviously fairly new judging by his post. Let him learn how to use protected data before you yell that it is the DEVIL CODE. Everything has its uses. Shit goto is still in c++ even though i have seen warnings to never use it in almost everything ive read.

Share this post


Link to post
Share on other sites
You seem a little hostile to be yelling at us for giving valid advice. We're stating that it isn't a good practice to not hide data members, nor is it the best to make them protected. We never told him not to. We're simply saying that these are the accepted practices, which when he becomes more advanced will help him in reading code and having others read his code. Sure he can use it, but we want him to know beforehand so he doesn't develop a habit that could be hard to break in the future.

Simple is simple, but simply done creates a simple bug that takes 12 hours to find. ;)

Share this post


Link to post
Share on other sites
Quote:
Original post by snk_kid
Quote:
Original post by MobileOak
Quote:
Original post by snk_kid
Making data members with protected access is most often "the sin of satan" and very contradictive, generally a sign of bad design unless there is real rationale for there use and there truely is such a tight coupling between parent & child types, in most case there isn't so don't fall into bad habbits.


Care to explain in more detail? I don't understand why derived classes shouldn't have access to their base class's member variables.


Because it's an implementation detail that doesn't need to be known, it should be pretty obvious why its called an abstraction, i even high-lighted the main terms coupling and also to enforce state invariants, polymorphic types and type inheritance in general is mainly about extending behaviours/operations not extending implementation, i'm not saying never, i'm say in most cases its abused without any rationale it may aswell be public. I'm not gonna go into any more details, just google it and you will get millions of hits about it.

In theory public virtual member functions considered are bad aswell but that is beyond the scope of this if you want to know more then google up on non-virtual interface idiom.


Even after ignoring the difficulties in understanding your post due to run-on sentances, mispelled words, and overuse of bold/italicized words, I'm having a difficult time understanding your reply. Due to your use of the phrase "sin of satan", horrendous misspellings and general grammar errors, I would normally have ignored your post. But since your rating is high, and you seem to know the terms involved, I thought you might have some insight into the situation that I could learn from, but all I've been able to comprehend from this most recent reply is "it's an implementation vs interface issue", and that I should "just google it".

This is hardly helpful, as googling phrases in your post leads me off on wild-goose chases. Googling for facts is great. Googling for the reasoning behind an argument is futile. Once again, I don't understand what you're talking about. Can you show me an example of why accessing inherited protected member variables is bad? I have used it many times, and if there is a better programming practice I would like to learn the reasoning behind it and how to use it.

This is the Beginner's forum. Most of the people reading it aren't going to understand your post, so please try to explain yourself better.

[Edited by - MobileOak on March 8, 2005 4:13:06 PM]

Share this post


Link to post
Share on other sites
Quote:
Original post by Roboguy
generally, it's a sign of bad design. Usually, the variables should be accessed through the members the base class provides.

Agreed. A class should be defined with a clear interface, which should be kept immutable to avoid having to alter code using the class—the implementation should be entirely hidden so that improvements and refactoring can be done without worrying about breaking something else. protected exposes details to inheriting classes, and is only slightly better than public—things can still break, just not as much.

Quote:

Also, you can access the base class's private fields (Note: this is a sign of even worse design) if you make it a friend, like this(it's been a while since I've used friends, so this may be a little off):
*** Source Snippet Removed ***
Remember: You should probably never use this, as it's usually bad design, just FYI.

Here I actually disagree. A class has two components: An interface, which is public and immutable, and an implementation, which users of your code shouldn't need to know anything about. However, I don't see why the entirety of the interface needs to consist of member functions, so long as it is well defined. Of course, you should only use friend to provide access to things that are part of the interface of the class, not random functions scattered here and there that happen to find access to private members more convenient.

Share this post


Link to post
Share on other sites
Quote:
Original post by Raymond_Porter420
an example of the most retarded code ive ever seen

class Point
{
GetX() { return x; }
GetY() { return y; }
SetX(int X) { x = X; }
SetY(int Y) { y = Y; }

private:
int x;
int y;
};


I understand that this looks like 'retarded code' to you. You're wondering why you should have to write all those accessor functions. The reason behind it is to protect the data from outside classes modifying it. If x and y were public, then any other code could modify a Point's x and y values without the Point knowing about it. Having the code written this way allows you to control that access.
Suppose that you have a game that always displays a Unit's location (represented by a Point class) in the GUI. If something other than the GUI modifies the location of the Unit, the GUI would like to know that. So let's say you add a function to SetX:

SetX(int X) { x = X; notifyGUI(); };

Now you are guaranteed that any time that Point's X is changed, the GUI is notified. Coding like this will prevent you from having to remember to notify the GUI every time you publicly access Point's X.

Does that make sense?

Share this post


Link to post
Share on other sites
Quote:
Original post by Jingo
If you have position in the base class, as you do, then the base class should surely provide an interface with which to act on the position values, the derived class can then be implemented in terms of this interface.


but what if you want the child class to effect his own position? you are saying doing so is bad practise? are using get / setters here considered bad practise? maybe slightly better then making them protected, but not as good as not needing them at all? but arent there many situations where you want the child class to directly effect his position?

Share this post


Link to post
Share on other sites
Quote:
Original post by MobileOak
[Lots o' stuff]

Does that make sense?

It makes sense, and that's one justification for it, but don't go overboard. Sometimes, all you need is a POD struct.

Share this post


Link to post
Share on other sites
Quote:
Original post by Miserable
Quote:
Original post by MobileOak
[Lots o' stuff]

Does that make sense?

It makes sense, and that's one justification for it, but don't go overboard. Sometimes, all you need is a POD struct.


That's true. I was merely trying to explain to him a reason for data encapsulation, since it's not intuitively obvious that its beneficial.

Share this post


Link to post
Share on other sites
I think your missing my point. Some stuff does need to be wrapped. Some vars need to be accessed through a function call because you might wana change them later. But some stuff is just data, just memory that you are using to hold some stuff. Since when was accesing a var such a bad thing. being object oriented has its advantages but it is possible to take it overboard. Telling someone private data is "the sin of satan" is what i consider overboard, exspecialy if the guy is still trying to learn what the "private" keyword does.

Share this post


Link to post
Share on other sites

This topic is 4666 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this