简体   繁体   中英

When does a class not contain a constructor?

I'm quite new to C++, but have general knowledge of other languages. Lately I've seen some tutorials about C++, and I have sometimes seen classes that do not have their own constructor, not even className(); . This might exist in the other languages as well, but I've never seen it before. I don't think I've seen them in use before either, so my question is: what are they for? And what are they? I tried googling this, but I don't know the name for it.. 'constructorless class' didn't give me much.

Without a constructor, is it possible to instantiate it? Or is it more of a static thing? If I have a class that contains an integer, but has no constructor, could I go int i = myClass.int; or something like that? How do you access a constructorless class?

If you don't explicitly declare a constructor, then the compiler supplies a zero-argument constructor for you. *

So this code:

class Foo {
};

is the same as this code:

class Foo {
public:
    Foo() {};
};


* Except in cases where this wouldn't work, eg the class contains reference or const members that need to be initialized, or derives from a superclass that doesn't have a default constructor.

If you do not specify a constructor explicitly compiler generates default constructors for you (constructor without arguments and copy constructor). So there is no such thing as constructorless class. You can make your constructor inaccessible to control when and how instances of your class created but that's a different story.

A class without a constructor is a good model for implementing an interface.

Many interfaces consist of methods and no data members, so there is nothing to construct.

class Field_Interface
{
  public:
    // Every field has a name.
    virtual const std::string&  get_field_name(void) const = 0;

    //  Every field must be able to return its value as a string
    virtual std::string         get_value_as_string(void) const = 0;
};

The above class is know as an abstract class. It is not meant to have any function, but to define an interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM