• 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

    • how big is your HDD that only has 100gb left? I take it this the main drive.  Is this a pc or laptop? I ask because changing hdd in pcs are much easier. You sure a good clean/purge of data wouldn't clear up space - have you ran disk cleanup? Which is part of windows..  You can for sure move data to your external drive, install programs to it, etc - but using it to store updates?   
    • How to record screen as GIF in Windows 11 by Taras Buria The Snipping Tool app is already quite a capable program for screenshots and screen recordings. Still, there is always room for improvement, and many users agree that the app needs the ability to save screen recordings as GIFs. Microsoft heard those users, and recent updates introduced the long-requested feature, allowing you to record your screen as a GIF. Here is how to do it. Record screen as a GIF in Windows 11 Note: By the time of publishing this article, GIF support in Snipping Tool is only available to Windows Insiders. However, you can enable that feature on stable Windows 11 releases as well; here is how: Go to store.rg-adguard.net, select ProductID in the first drop-down, paste 9MZ95KL8MR0L into the search box, and select Fast in the last drop-down. Press the checkmark button. Find and download Microsoft.ScreenSketch_2022.2505.21.0_neutral_~_8wekyb3d8bbwe.msixbundle in the list of apps. The version number could be newer, just make sure you are downloading an msixbundle file. Note that the browser will warn you about downloading a potentially harmful file. Open the file and click Update. Download ViveTool from GitHub and unpack the files in a convenient and easy-to-find folder. Run Command Prompt as Administrator and navigate to the folder containing the ViveTool files with the CD command. For example, if you have placed ViveTool in C:\Vive, type CD C:\Vive. Type vivetool /enable /id:47081492 and press Enter. The steps above might seem a bit tedious, but that is the only way to get GIF support in Snipping Tool without enrolling your device in the Windows Insider program. We will update the article once the feature is publicly available, so there is no need to jump through all the hoops just to make it work. Tip: You can always roll back Snippint Tool to the latest version from the Microsoft Store by uninstalling it and downloading it again. Now, with GIF support enabled in Snipping Tool, here is how to save a screen recording as a GIF in Windows 11: Press Win + Shift + S, select screen recording mode and record whatever you want. After the recording is over, Snipping Tool will open your video so that you can view, trim, or save it. At this point, all you have to do is click the GIF button in the upper-right corner. On the next screen, select your GIF quality and click Export to save as a file or Copy to copy it to the clipboard. And that is how you save screen recordings as GIFs in Windows 11. Note that Snipping Tool can only save GIFs for up to 30 seconds. Anything beyond that will be cut off. You might think that Clipchamp, Windows 11's built-in video editor, is a good option when you want to save a screen recording as a GIF. However, it really sucks at that. The video duration is capped at just 15 seconds, which is even worse than the Snipping Tool, and the output resolution is hilariously low. The latter makes it impossible to distinguish any details, and all you get is a blurry, pixelated mess. No, Clipchamp is not a good option for that. If you want to create GIFs that are longer than 30 seconds, a good option is to go with apps like ShareX, which is extremely flexible and customizable (and also free, which makes it one of our favorite must-have apps for Windows 11). Alternatively, you can record a video using the Snipping Tool and then convert it to a GIF using web-based services like Ezgif, another great free utility. Keep in mind that the larger your video resolution and the longer its duration, the bigger the final GIF size. Depending on the settings, GIFs could reach hundreds of megabytes, so you have to set your expectations correctly (and so do the settings, too).
    • I'll give you an example of "the settings problem." As awful as the HP Smart app is, it's magnitudes more useful than Settings when I need to do some deep dive stuff on my HP Officejet.
    • I hate to defend Apple but this marketing and they are only "desperate" to move from #3 to #1 for biggest company in the world.
    • There's very granular stuff in the legacy Control Panel that will probably never be accessible from settings. But that stuff will still be there if you know where to look.
  • Recent Achievements

    • Week One Done
      DXB APPS earned a badge
      Week One Done
    • One Month Later
      DecaffKnight94 earned a badge
      One Month Later
    • Dedicated
      S.P earned a badge
      Dedicated
    • One Month Later
      adxnksd42031 earned a badge
      One Month Later
    • Rising Star
      aphanic went up a rank
      Rising Star
  • Popular Contributors

    1. 1
      +primortal
      661
    2. 2
      ATLien_0
      253
    3. 3
      Michael Scrip
      234
    4. 4
      Steven P.
      155
    5. 5
      +FloatingFatMan
      149
  • Tell a friend

    Love Neowin? Tell a friend!