• 0

[C++] Accessing private member variables


Question

Hi, I'm new to C++ and OOP. I've been having a problem with a concept.

class samp
{
	int i;
public:
	samp(int n)
	{
		i = n;
	}
	int func(samp ob)
	{
		return ob.i;
	}
};

Now, i is a private member of the class samp. So, how can the parameter ob access i directly? I know func(ob) is a member function of the class. But I thought private members can only be accessed with a this pointer.

Can anyone explain why the above code works?

10 answers to this question

Recommended Posts

  • 0
  On 14/09/2011 at 16:08, kInG aLeXo said:

You need the this pointer only if the parameter name is same as a variable name in the class (public or private, because it does shadow the class variable in that case).Otherwise, this is not needed, and is implicitly "included".

I understand that. But, my real question was, how can "ob", which is a parameter of the fuctions func(), directly access ob.i? Doesn't that break the whole idea of having private variables?

  • 0
  On 14/09/2011 at 16:13, Solid Knight said:

Because i isn't private.

This is C++ not Java, i is private by default (he didn't include it in the public, so its by default implicitly private).

  On 14/09/2011 at 16:13, Gigi Buffon said:

I understand that. But, my real question was, how can "ob", which is a parameter of the fuctions func(), directly access ob.i? Doesn't that break the whole idea of having private variables?

I had this very exact mistake in an exam..

Turns out, if the calling class is of the same type, it can actually access the private variables, and even the private constructors and functions of another instance of the same class.(ie: this code works only because func is member of samp class, which is same class of ob parameter, if func was member of another class it won't work).

  • 0

If you know what friend is, you can think of a class being a friend of itself. This allows it to access private members of another object of the same class.

I'm sure there are several reasons for this. The main one I find is that when writing copy constructors you need to access private variables that you might not otherwise want to be exposed.

  • 0
  On 14/09/2011 at 16:16, kInG aLeXo said:

Turns out, if the calling class is of the same type, it can actually access the private variables, and even the private constructors and functions of another instance of the same class.(ie: this code works only because func is member of samp class, which is same class of ob parameter, if func was member of another class it won't work).

Thanks for explaining. I was thinking the same, but couldn't find any reference for it.

  • 0
  On 14/09/2011 at 16:23, Lant said:

If you know what friend is, you can think of a class being a friend of itself. This allows it to access private members of another object of the same class.

I'm sure there are several reasons for this. The main one I find is that when writing copy constructors you need to access private variables that you might not otherwise want to be exposed.

I only know about friend functions, not friend classes. So I can't understand how a class can be a friend of itself. Maybe you meant the member functions of a class are friends of that class? If that's the case, then everything makes sense.

Edit: Just read up on friend classes. Yes, your post makes plenty of sense now. Thank you.

  • 0
  On 14/09/2011 at 16:26, Gigi Buffon said:

Thanks for explaining. I was thinking the same, but couldn't find any reference for it.

In many cases just trust the compiler, even if you find in some reference a different thing.If you can, use GCC instead of Visual Studio (for Windows I recommend Code::Block with MingW), its much better compliant to the C++ standards.

  • 0

" the private keyword specifies that those members are accessible only from member functions and friends of the class. This applies to all members declared up to the next access specifier or the end of the class." private (C++)

It turns out encapsulation is done at the class level, not at the object level. An object of type Foo can access the private members of another object of type Foo and that doesn't break encapsulation because both objects are of the same type. In other words, they know how the other is laid out since it's of the same type. So they're only using information already available to them. Encapsulation is broken when a type Y makes an assumption about type X's implementation.

  • 0
  On 14/09/2011 at 16:34, kInG aLeXo said:

If you can, use GCC instead of Visual Studio (for Windows I recommend Code::Block with MingW), its much better compliant to the C++ standards.

What does this have to do with the OP?

This is just an opinion which imo is plain rubbish. Compliant to what standard? C++11? There are no compilers fully compliant to that.

Imo Visual C++ has a superior debugger than GCC and Visual studio is a better IDE than Code::Blocks.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • I'm just thinking out loud for a second...could it be the cookie prompt that kicks up the adblock message? The reason I ask is that on Firefox (ad-block enabled but not for Neowin) I don't get the cookie consent option. But if I open Chrome (ad-block disabled) and go to the Neowin I get the cookie banner and then it's all fine. Some form of conflict of interest between the banners? It's probably nothing, but that's what I have just noticed.
    • SoundSwitch 6.14.1 by Razvan Serea SoundSwitch is a Windows app that makes switching your sound devices super easy. Normally, changing speakers or microphones means clicking through annoying menus. With SoundSwitch, you just press a shortcut key (like Ctrl + Alt + F1) — and it switches to the device you want. You can set different keys for speakers, headphones, microphones, or even groups of devices. It also lets you mute your mic with a hotkey and shows a clear banner so you know it's muted. It runs in the background, shows up in your taskbar, and starts with Windows if you want. It’s perfect if you use multiple audio devices and get tired of clicking around every time you want to change one. SoundSwitch features: Customizable Hotkeys: Assign specific key combinations to switch between audio devices quickly. ​ Playback and Recording Device Switching: Toggle between selected playback and recording devices without navigating through system menus. ​ Microphone Mute Toggle: Use hotkeys to mute or unmute the default microphone. ​ Persistent Mute Notification: Displays a compact banner indicating the microphone's mute state, which remains visible until the microphone is unmuted. ​ Profile Management: Create profiles to switch between specific combinations of playback and recording devices using designated hotkeys. ​ Command Line Interface (CLI): Control SoundSwitch through command-line commands for device switching, microphone mute control, and profile management. ​ Auto-Start with Windows: Option to launch SoundSwitch automatically upon system startup. ​ Multi-Language Support: Includes translations for various languages, such as Tamil. ​ Notification Customization: Choose the type of notifications displayed for device switching and mute status. ​ Support for Various Hotkey Combinations: Accepts single keys like PrintScreen, Pause, Home, End, and function keys as hotkeys. ​ System Tray Integration: Access settings and perform device switching directly from the system tray icon. ​ Device Grouping: Organize multiple devices into groups for streamlined switching. ​ User-Friendly Interface: Provides an intuitive setup and configuration process for users. ​ Open-Source Development: Available on GitHub for community contributions and transparency. ​ Regular Updates: Actively maintained with new features and bug fixes. ​ SoundSwitch 6.14.1 changelog: Bug Fixes settings: fix opening settings crashing the application when using CLI or opening SoundSwitch again (b3dca74) Languages Amharic: Added About translation using Weblate (8a40dab) Japanese: Translated About using Weblate (3541994) Japanese: Translated Settings using Weblate (ca5b2fe) Japanese: Translated Settings using Weblate (39a2340) Japanese: Translated Tray Icon using Weblate (1286b92) Japanese: Translated Update Download using Weblate (1c2c658) Norwegian Bokmål: Translated Settings using Weblate (5aaf243) Portuguese: Translated Settings using Weblate (e11f18d) Swedish: Translated Settings using Weblate (8b7b738) Download: SoundSwitch 6.14.1 | 45.4 MB (Open Source) View: SoundSwitch Website | Github | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Wow, the usual crowd is out in full force again — the trolls who think sarcasm is insight, the doom prophets who scream 'web apps = surveillance', and the armchair devs who still think Outlook 2003 was peak tech. Here’s a wild idea: maybe evaluate an app on what it does instead of what your paranoia imagines it’s doing. The new Outlook is fast, clean, and tightly integrated. No, it’s not perfect — what app is? But if your main tech critique is 'It’s different and Microsoft is evil', you’re not reviewing software. You’re just rehearsing your trust issues. Don't like it? Cool. But at least bring something to the table besides tired one-liners and Chicken Little routines. Some of us actually use this stuff and prefer practical feedback over pointless whining.
    • And they will only last thousands of years underground we don’t know where.
    • Went on a bit of a Bethesda binge recently after the Oblivion remaster release, although not in a positive way. I liked the OG Oblivion and completed it nearly 20 years ago, but the remaster didn't resonate with me in the same way - just feels like it hasn't aged well, gameplay-wise - so I moved onto finally giving Skyrim a go after owning it for so many years, and I had what I've been informed was a classic introduction to the game... It got stuck shortly after that at the point where an NPC's supposed to be thrown on the chopping block and beheaded; everyone just stood in place twiddling their thumbs and not saying their lines (this was the Xbox version too of the 'Special Edition' with no mods enabled). Did the same every time I reloaded, so took it as a sign that even the game was telling me to just bin it, so I did and moved onto Fallout 4, which is alright so far (touch wood).
  • Recent Achievements

    • Reacting Well
      James courage Tabla earned a badge
      Reacting Well
    • Apprentice
      DarkShrunken went up a rank
      Apprentice
    • Dedicated
      CHUNWEI earned a badge
      Dedicated
    • Collaborator
      DarkShrunken earned a badge
      Collaborator
    • Rookie
      Pat-Garrett went up a rank
      Rookie
  • Popular Contributors

    1. 1
      +primortal
      341
    2. 2
      snowy owl
      167
    3. 3
      ATLien_0
      161
    4. 4
      +FloatingFatMan
      161
    5. 5
      Xenon
      127
  • Tell a friend

    Love Neowin? Tell a friend!