• 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'd concur too, as an informed enthusiast I'd find it a good deal, but your average Joe just wants cheap as possible and it's hard to beat Amazon or Ebay builds for that.
    • Now you know how many would-be Windows 11 users felt. I’m not justifying any of it, but MS and Apple both do it.
    • An Air India plane with 242 people on board crashed Thursday near a major international airport in the western Indian city of Ahmedabad, the airline and the country's government said. https://www.nbcnews.com/world/asia/air-india-plane-crashes-indias-ahmedabad-airport-rcna212545
    • NTLite 2025.06.10473 by Razvan Serea NTLite is a Windows configuration tool that allows you to modify your existing Windows install or an image yet to be deployed, remove Windows components, configure and integrate, speed up the Windows deployment process. Reduce Windows footprint on your RAM and storage drive memory. Remove components of your choice, guarded by compatibility safety mechanisms, which speed up finding that sweet spot. Windows Unattended feature support, providing many commonly used options on a single page for easy setup. Easily integrate a single or multiple drivers, update or language packages. Package integration features smart sorting, enabling you to seamlessly add packages for integration and the tool will apply them in the appropriate order, keeping hotfix compatibility in check. One of the important new features of NTLite (compared to its predecessors) is the ability to modify an already installed the operating system, by removing unnecessary components. Supports Windows 11, 10, 8.1 and 7, x86 and x64, live and image. Server editions of the same versions, excluding support for component removals and feature configuration. ARM64 image support in the alpha stage. Does not support Checked/Debug, Embedded, IoT editions, nor Vista or XP. NTLite 2025.06.10473 changelog: Upgrade UI: Text size now set as host, more readable on some systems Post-setup: Loading progress improvement for the 99% delay Components: ‘Snipping tool’ compatibility option UI-Translation: Thanks for Romanian (Coman) Fix Updates: Parallel WinRE integration getting stuck Updates: Download overwrite previous Defender updates Settings: Win10 News widget disabling Download: NTLite 64-bit | 21.5 MB (Free, paid upgrade available) Download: NTLite 32-bit | 19.3 MB Link: NTLite Home Page | NTLite Features | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Week One Done
      elsafaacompany earned a badge
      Week One Done
    • Week One Done
      Yianis earned a badge
      Week One Done
    • Veteran
      Travesty went up a rank
      Veteran
    • One Month Later
      somar86 earned a badge
      One Month Later
    • Week One Done
      somar86 earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      505
    2. 2
      ATLien_0
      259
    3. 3
      +Edouard
      185
    4. 4
      +FloatingFatMan
      180
    5. 5
      snowy owl
      132
  • Tell a friend

    Love Neowin? Tell a friend!