user8759451
user8759451

Reputation: 1

segmentation fault while calling base class constructor in derived class

i'm getting a segmentation fault when i call the base class constructor from the derived class in c++ .i'm using the below code.

#include <iostream>
using namespace std;
class A {
protected:
    int x;

public:
    A()
    {
        x = 10;
        cout << "value of X in A is" << x << "\n";
    }
};
class B : A {
private:
    int z;

public:
    B()
    {
        A::A();
        z = 20;
        cout << "value of z in B is" << z << "\n";
    }
};
int main()
{
    B* logger;
    logger = new B;
}

while building i have used the -fpermisson option to build this code else it was showing the below error.

main.cpp: In constructor ‘B::B()’:
main.cpp:19:7: error: cannot call constructor ‘B::A’ directly [-fpermissive]
  A::A();
       ^
main.cpp:19:7: note: for a function-style cast, remove the redundant ‘::A’

when i try to run this code i'm getting a segmentation fault. To understand the issue i did some debugging and could see that when i try to create the object of B the constructor of A getting called indefinitely that create the segmentation fault(i think so). I'm not that expert in C++ please help me to understand what i did wrong here. i'm using linux environment to test this.

Upvotes: 0

Views: 271

Answers (1)

cigien
cigien

Reputation: 60218

You can't call a constructor directly like this:

A::A();  // error

Using additional flags to produce a program is fine, except that you can't expect the program to work.

If you want to call a base class constructor, you can do it in the member initializer list:

B() : A()
{
    z=20;
    cout<<"value of z in B is"<<z<<"\n";
}

In this case, it's not necessary because the default constructor will get called anyway.

Upvotes: 4

Related Questions