-
May 16th, 2008, 11:59 PM
#1
[C++] What are the differences between classes and structs?
Q: What are the differences between classes and structures in C++?
A: - Classes have private members by default, whereas structures have public members by default:
Code:
class CFoo
{
void f() {}
};
struct SFoo
{
void f() {}
};
int main()
{
Cfoo c;
c.f(); // error: 'CFoo::f' : cannot access private member declared in class 'CFoo'
SFoo s;
s.f(); // OK
return 0;
}
- Classes have private inheritance by default, whereas structures have public inheritance by default:
Code:
class CBase
{
public:
void f() {}
};
struct SBase
{
public:
void f() {}
};
class CFoo : CBase
{
};
struct SFoo : SBase
{
};
int main()
{
CFoo c;
c.f(); // error: 'CBase::f' not accessible because 'CFoo' uses 'private' to inherit from 'CBase'
SFoo s;
s.f(); // OK
return 0;
}
Last edited by cilu; May 27th, 2008 at 01:45 PM.
Reason: renamed entities
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|