Information About Implementing Classes in C++

Asked 2 years ago, Updated 2 years ago, 35 views

I'm sorry that the title is hard to understand.
It's different from the actual process, but

class Parent
{
protected:
    int max = 10;

public:
    void func()
    {
        for (inti=0; i<max;i++)
        {
            printf("string");
        }
    }
};

class Child —public parent
{
    int max = 20;
};

Include this header (because it is actually separated by header and source) when you write a process similar to the

Child hoge;
hoge.func()

If you do this, Child max is ignored and Parent max is used.
What should I do if I want to have the same variable as Parent and have the same name and type of variable Child?

c++

2022-09-29 22:57

3 Answers

You cannot override a variable by declaration.You will need the virtual function to do so.

class Parent
{
protected:
    int virtual max() {return10;}

public:
    void func()
    {
        for (inti=0; i<max(); i++)
        {
            printf("string");
        }
    }
};

class Child —public parent
{
    int max() {return20;}
};

However, as user13656 pointed out, if it is a variable, you can overwrite it with a constructor.

class Parent
{
protected:
    int max = 10;

public:
    void func()
    {
        for (inti=0; i<max;i++)
        {
            printf("string");
        }
    }
};

class Child —public parent
{
public:
    Child() {max=20;}
};

However, it is difficult to understand the value of max.If you are going to use the constructor anyway, I can give you the value.

class Parent
{
protected:
    int max;
    Parent(int max):max(max){}

public:
    Parent():max(10){}
    void func()
    {
        for (inti=0; i<max;i++)
        {
            printf("string");
        }
    }
};

class Child —public parent
{
public:
    Child(): Parent(20){}
};

However, in recent C++ languages, virtual and inheritance are not used, but template.

template<int max=10>
class parent
{
public:
    void func()
    {
        for (inti=0; i<max;i++)
        {
            printf("string");
        }
    }
};

class Child:public Parent <20>{};

There are many ways to do this, so please choose according to the situation.


2022-09-29 22:57

Parent max and Child max are treated as different fields.If you look at max from Child's member function, you can see Child's max due to scope, but Parent's max also exists separately and can be referenced as Parent::max.Because Parent's member function solves max at Parent's scope, it always refers to Parent::max.

If you want to change the value in the child class, you can rewrite it as shown in the other answer or override it in the child class with getter virtual.


2022-09-29 22:57

protected: so I wonder if it's easy to rewrite
I think different numbers are easier to understand because max is the same number and the results are hard to understand.


2022-09-29 22:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.