简体   繁体   中英

Inherited class's constructor is not running

I have 3 classes, A,B, and C.

Edited code.

#include <iostream>

class A {
    public:
        virtual void print() {
            std::cout << "A" << std::endl;
        }

        A() : x(0) {} // constructor

        void SetX (int tmp){
            x = tmp;
        }
        
        void printX() {
            std::cout << "x = " << x << std::endl;
        }

    private:
        int x;
};


class B : public A {
    public:
        virtual void print(){
            std::cout << "B" << std::endl;
        }
    
        B(int tmp) : A() {
            SetX(tmp);
        }

};

class C : public B {
    public:
        virtual void print(){
            std::cout << "C" << std::endl;
        }
    
        C(int tmp) : B(tmp) {
            std::cout << "Debug print" << std::endl;
        }
};

int main() {
    B* b = new B(1);
    C* c = new C(2);
    
    b->print();
    b->printX();
    c->print();
    c->printX();
    
    return 0;   
}

print for b->printX = 1 and for c->printX = 0

when creating object B everything is work just fine.

but when creating object C the default value of class A (var x) is still 0 (default value).

i added debug line inside the constructor of class C, but i didnt see it in logs, looks like the constructor is not running. i did the same thing in the constructor of class B when creating only object C and i didnt see any debug print too.

There no any compiling error for this code. build finish successfully.

The following is legal and working C++. Your code was not legal C++.

I added a void printX() method to class A to illustrate the example.

#include <iostream>

class A {
    public:
        virtual void print() {
            std::cout << "A" << std::endl;
        }

        A() : x(0) {} // constructor

        void SetX (int tmp){
            x = tmp;
        }
        
        void printX() {
            std::cout << "x = " << x << std::endl;
        }

    private:
        int x;
};


class B : public A {
    public:
        virtual void print(){
            std::cout << "B" << std::endl;
        }
    
        B(int tmp) : A() {
            SetX(tmp);
        }

};

class C : public B {
    public:
        virtual void print(){
            std::cout << "C" << std::endl;
        }
    
        C(int tmp) : B(tmp) {
            std::cout << "Debug print" << std::endl;
        }
};

int main() {
    B* b = new B(1);
    C* c = new C(2);
    
    b->print();
    b->printX();
    c->print();
    c->printX();
    
    return 0;   
}

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