Code Snippets

  

C++ Source Code


Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 131,108 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 2,161 people online right now. Registration is fast and FREE... Join Now!





Accessing Private Data Members in Classes

This code shows you how to access private data members in classes without using the friend keyword.

Submitted By: born2c0de
Actions:
Rating:
Views: 11,091

Language: C++

Last Modified: March 2, 2005

Snippet


  1. /*
  2.                ACCESSING PRIVATE DATA MEMBERS IN C++
  3.                                     -SANCHIT KARVE
  4.                                      born2c0de@hotmail.com
  5.               */                     
  6.  
  7. #include <iostream.h>
  8. #include <string.h>
  9. #include <conio.h>
  10.  
  11.  
  12. class bestcoder
  13. {
  14.   private:
  15.  
  16.      char name[40];
  17.      char grade;
  18.      int age;
  19.  
  20.   public:
  21.  
  22.             bestcoder(char* nam="Some Dude",char gr='A',int saal=25)
  23.       {
  24.          strcpy(name,nam);
  25.          grade=gr;
  26.          age=saal;
  27.       }
  28.  
  29.       friend ostream& operator <<(ostream& s,bestcoder b);
  30. };
  31.  
  32. ostream& operator <<(ostream& s,bestcoder b)
  33. {
  34.   s<<"Best Coder  :"<<b.name<<endl
  35.        <<"His Rating  :"<<b.grade<<endl
  36.    <<"Current Age :"<<b.age<<"\n\n\n";
  37.    return s;
  38. }
  39.  
  40. struct hackit
  41. {
  42.   char name[40];
  43.   char grade;
  44.   char age;
  45. };
  46.  
  47.  
  48. void main()
  49. {
  50.  bestcoder bc;
  51.  cout<<bc;
  52.  void* ptr=&bc;
  53.  struct hackit* bettercoder=(hackit*)ptr;
  54.  bettercoder->grade='F';
  55.  bettercoder->age=56;
  56.  cout<<bc;
  57.  strcpy(bettercoder->name,"Sanchit Karve");
  58.  bettercoder->age=14;
  59.  bettercoder->grade='A';
  60.  cout<<bc;
  61.  getch();
  62. }
  63.  
  64.  
  65.  

Copy & Paste


Comments


aquene533 2007-12-07 22:41:12

I made a small error when I defined my friend member function in main... the examples provided me with the insight necessary to track down and correct my silly error! Thank you! This website is a great resource!


Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month