dada wrote:
The following source file does not compile.
#include <cstdio>
class X {
public:
X() { i = 100; }
private:
int i;
};
int main()
{
X x;
printf("%d\n", x.i);
}
Add one line (having one semicolon) to the definition of X that in
turn makes the file compilable. itsValue shud b private.
Firdays [sp] are bad days to post issues that can
be resolved by consulting the FAQ.
http://www.parashift.com/c++-faq-lit...d-objects.html http://www.parashift.com/c++-faq-lite/friends.html http://www.parashift.com/c++-faq-lite/newbie.html
Here is the reason. You have declared the variable 'i'
as private (having private accessibility). "private"
means that only class member functions have access
to those items. Any function outside of the class
cannot see nor access a private item.
The compiler is complaining that the main() function
is trying to access a private data member.
If you want a private member to be displayed, you
either have to create a member function to do that:
class X
{
// as above
public:
void print(void)
{ printf("%d\n", i);}
void print_cpp_style(void)
{ cout << i << endl;}
void print_better_style(ostream& out)
{ out << i; }
};
int main(void)
{
X junk;
junk.print();
junk.print_cpp_style();
junk.print_better_style(cout);
cout << endl;
return 0;
}
or you will have to place the member variable
into a public section:
class X
{
public:
int i;
};
Also, due yourself a favor and look up "initialization
list" in your favorite text book or help file.
--
Thomas Matthews
C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq:
http://www.parashift.com/c++-faq-lite
C Faq:
http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book