Using inheritance to initialize parameters in C++

how to initialize base class member from derived class c++
c++ inheritance constructor with parameters
how to call base class constructor from derived class in c++
how will you transfer values from derived class constructor to base class constructor?
constructor and destructor in inheritance in c++
calling base class constructor from derived class in c#
c inherit constructor from base class
single inheritance using constructor in c++

I have read that it is not good to overuse inheritance in C++. I have a simple example where I would like to know if it is good or bad to use it to initialize values in the base class constructor.

Let's say I have a class Animal :

class Animal{
protected :
Animal(std::string name, std::string category);
std::string m_name;
std::string m_category;
};

Is it good to create a specific class for each animal the application is going to use for example :

class Bear : public Animal{
public :
Bear():Animal("Bear", "Mammal"){
}
};

Of course that means that if I have 100 animals, I need 100 classes, and that feels awkward to my eyes. In this example, I am using inheritance only to initialize values, there won't be any specific virtual methods involved.

Thanks

Broadly speaking, the choice of whether to create derived classes or to just have data members on one class becomes a question of whether more classes actually help with the situation you're trying model/solve in the software.

For instance, an application that cares about how vehicles travel might have different classes for Car, Boat, Airplane, Helicopter, etc. On the other hand an application that only cares about the existence of vehicles (say it's for tracking what a business owns) might only need a single class for Vehicle in general.

As one rule of thumb, ask yourself if the derived classes are actually going to behave differently in any way, as far as what the rest of your program is concerned with. If yes, then derived classes may be what you want. If no, then probably not.

In your specific case, is there going to be any real difference between

Bear bear;

and

Animal bear("Bear", "Mammal");

If not, then a derived class of each type of Animal sounds excessive (100 derived classes sounds excessive in general) and you probably want to do something else depending on how you want to store the data. Perhaps making a list or map of Animal instances.

11.4 — Constructors and initialization of derived classes, However, C++ prevents classes from initializing inherited member variables in the Copy constructors with a single parameter are converting constructors. Inheritance enables you to create new classes that reuse, extend, and modify the behavior defined in other classes. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. A derived class can have only one direct base class. However, inheritance is transitive.

Usually, it's not a good practice to have members in the base class. Rather than that, create an interface and provide an implementation in the derived class returning the values:

class Animal {
protected:
    virtual std::string getName() const;
    virtual std::string getCategory() const;
};

class Bear : public Animal{
public:
    virtual std::string getName() const override {
        return std::string("Bear");
    }

    virtual std::string getCategory() const override {
        return std::string("Mamal");
    }
};

C++ Order Of Constructor Call with Inheritance, Order of Constructor Call with Inheritance in C++. Base class constructors are always called in the derived class constructors. Whenever you create derived� Implementing inheritance in C++: For creating a sub-class which is inherited from the base class we have to follow the below syntax. Syntax:. class subclass_name : access_mode base_class_name { //body of subclass };

Inheritance is useful when you have different cases of implementation but still have the same working base behind. In your case if the only difference between all your animals is the name and category and that there's no specific implementations then I personally think this is not useful.

However what could be improved in your case is the need of 2 arguments that define the same thing (a Bear is always a mammal for example). Maybe a map could fix this issue in your case?

Building Inheritance, The C++ syntax that implements an inheritance relationship is part of the class constructor and of passing appropriate data through the parameters. C++� Inheritance (Derived and Base Class) In C#, it is possible to inherit fields and methods from one class to another. We group the "inheritance concept" into two categories: Derived Class (child) - the class that inherits from another class; Base Class (parent) - the class being inherited from; To inherit from a class, use the : symbol.

Making a class for each animal seems excessive. I did a school work before where I used an Animal class and I made the derived class into Predator and Prey. So, make the derived ones be specific types of animal, like Mammal, Fishes, etc. For your example, you can just use the single Animal class and call that Animal bear.

Constructors (C++), class Box { public: // Default constructor Box() {} // Initialize a Box with equal have no parameters, but they can have parameters with default values. C++ In general, it is best to use inheriting constructors when the derived� Using Constructors (C# Programming Guide) 07/20/2015; 4 minutes to read +12; In this article. When a class or struct is created, its constructor is called. Constructors have the same name as the class or struct, and they usually initialize the data members of the new object. In the following example, a class named Taxi is defined by using a

Constructors and member initializer lists, In the definition of a constructor of a class, member initializer list Constructors are declared using member function declarators of the following form: class- name ( parameter-list(optional) ) except-spec(optional) attr(optional), (1) does not propagate down the inheritance hierarchy) and virtual calls (but� Observe the line public Class2(int a, int b, int c) : base(a, b) Now, here I am calling the base class constructor, using base(a, b) Now, when I create the instance of the derived class as Class2 obj2 = new Class2(2, 3, 4); Thus, the base class constructor, that takes two parameters is called first and then the derived class constructor.

Using-declaration - cppreference.com, The entire initialization is treated as a single function call: initialization of the parameters of the inherited constructor is� using Alias = System; namespace Library { public class C : Alias::Exception { } } This works, but if a type named Alias were to subsequently be introduced, Alias. would bind to that type instead. Using Alias::Exception ensures that Alias is treated as a namespace alias and not mistaken for a type. See also. C# Programming Guide; Namespaces

Initialization of base classes and members (C++ only), Initialization of base classes and members (C++ only). Constructors can initialize their members in two different ways. A constructor can use the arguments passed � But, if we want to call parameterized contructor of base class, then we can call it using super(). The point to note is base class constructor call must be the first line in derived class constructor. For example, in the following program, super(_x) is first line derived class constructor.

Comments
  • Thanks for your answer ! There won't be any difference, it's more an architecture question, because I would like to avoid the creation of Animals using the Animal constructor, so probably encapsulating it into a factory with an enum for each animal is the best solution?
  • @DarkVapor Indeed, that's another option. Perhaps something like an enum AnimalType and then a function like Animal* CreateAnimal(AnimalType type) which constructs them as necessary. That way you can keep the details of construction nicely separated from the rest of the code that uses the objects.
  • I do think this is the best indeed !
  • Are you sure about that? That seems very dirty to me ;-)
  • I don't think it's dirty at all, it's cleaner than having the base class polluted by members that don't have to be there. But if this is a good solution for you depends on what you're trying to achieve. What's exactly your use-case?
  • It seems dirty to me because that's the principle of constructors to initialize values in. I would keep virtual methods to redefine different behaviors in the class, rather than using it your way. Not to mention that if you have 100 classes, you will need to write a lot more code if you need to redefine those methods for each class.
  • Honestly, if the example you've given is not just an example but an actual use-case, don't use inheritance. There is no point to have a separate class for each animal. That is in case you're not planning to extend each animal class with some behaviour exclusive to every animal. Then you could just have one Animal class and pass the name and category to the constructor and just use this class. However, in case you are planning to extend each animal class with more functionality, put the members in the derived classes and create a pure interface (abstract class) that is common for all animals.