The difference between class and struct in C + +

Source: Internet
Author: User
Tags constructor inheritance

It's an old question. Today a little summed up, there are missing places and the wrong place also hope everyone to add.

About using curly braces to initialize

Class and struct cannot be initialized with curly braces if the constructor is defined.

If no constructor is defined, struct can be initialized with curly braces.

If you do not define a constructor and all member variables are public, you can initialize them with curly braces.

About default access rights

The default member access permissions in class are private, and struct is public.

About inheritance Methods

class inheritance defaults to private inheritance, and struct inheritance defaults to public inheritance.

And look at the following code (see the compiler for the error message):

class T1
{
 public:
  void f()
  {
   cout<<"T1::f()"<<endl;
  }
 int x,y;
};
struct T2
{
 int x;
 void f(){cout<<"T2::f()"<<endl;}
};
struct TT1 : T1
{
};
class TT2 : T2
{
};
int main()
{
 TT1 t1;
 TT2 t2;
 t1.f();
 t2.f();
}

About templates

In the template, the type parameter can be preceded by class or TypeName, and if the struct is used, the meaning is different, struct followed by "non-type template parameter", and class or typename followed by the type parameter.

template <struct X>
void f(X x)
{
}
//出错信息:d:codecpptestcpptestcpptest.cpp(33) : error C2065: 'X' : undeclared identifier

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.