1

Can I have const variable in a c++ interface? Is it valid as part good design? (Not wrt syntax but as per good practices).

For example, if I want a class interface "modellable" which is implemented by models and I have a variable isModel in the interface which will be set to TRUE when instantiation of model class is done.

So, I can make isModel a const bool. Isnt it?

  • 1
    C++ has no interfaces. Are you talking about an abstract base-class? – Philipp Sep 18 '16 at 16:57
  • 1
    C++ has interfaces. It just doesn't have an interface keyword. What it has instead are header files which certainly can have consts. – candied_orange Sep 18 '16 at 17:20
  • 1
    @CandiedOrange it also has classes with no method definitions, only pure virtual methods, which are much similar to interface keyworded constructs from other languages – Caleth Sep 18 '16 at 18:37
  • 2
    @Caleth very true. Interface used to be a perfectly reasonable word to use to describe how to interact with a bit of code. Then java messed everything up by making interface also be a keyword for a kind of type. Now I'm forever explaining which I mean. – candied_orange Sep 18 '16 at 18:42
  • 2
    @CandiedOrange I blame MS and C# for that most of the time. Drives me nuts, I've resorted to using interface and API. But then, someone inevitably thinks I'm talking about a web service and... I give up. – RubberDuck Sep 18 '16 at 20:47
2

An interface in C++ can be defined with the help of an abstract class. So, if the question is if you can have a constant member variable you can. However, a constant member variable cannot be changed during program execution. You can do this with the help of a configurable flag provided in the interface.

I will strongly advice against the above for 2 reasons:

1) Interfaces should normally have member functions. An interface is a collection of abstract methods. The main functionality of an interface is to serve as a bridge between the user and the inner functionality. This interface should more or less remain constant throughout the product lifecycle. Therefore, having a constant bool does not make sense from an OOP standpoint.

2) If you want to initialise an object, a constructor is the best way of making sure that it happens. Therefore, initialisation then depends on object instantiation in your product and you will not need to write support functions to do so.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.