Sti
Sti

Reputation: 8484

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?

Upvotes: 1

Views: 1305

Answers (3)

Thomas Matthews
Thomas Matthews

Reputation: 57678

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.

Upvotes: 0

Slava
Slava

Reputation: 44238

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.

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

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, e.g. the class contains reference or const members that need to be initialized, or derives from a superclass that doesn't have a default constructor.

Upvotes: 4

Related Questions