Instantiating derived class causes crash?

Hello, I'm facing a rather strange problem that I need help on solving... So when I instantiate a derived class (HomePC, GamingPC or WorkstationPC) from the base abstract class (PC), I get segmentation fault message. What's even more strange is that, on the IDE (Code::Blocks) the program runs fine the first 2 times I try to instantiate, but the 3rd time, instead of crashing, the while loop terminates. The crash occures on Putty though, but not on the IDE?

I uploaded the code on pastebin because it's too big to fit here.

Instatiation that causes the crash happen on lines 306, 311 and 316.

https://pastebin.com/myPC0fuj

I appreciate the help!
You should also post what you expect people to type in to get the thing to work / crash.

1
2
3
4
    HomePC(string _model) : PC(model, "MacOS", 2, 0, 2, 1, 4, 256, 800, 0, 0)
    {
        this->model = _model;
    }

At the point you call the base class, model is uninitialised.
You should also post what you expect people to type in to get the thing to work / crash.

Yeah you are right, the crashes occur when you type "new", then one of the three: homepc, gamingpc or workstationpc and then any name, for example:
new gamingpc myPC

If I execute that command 3 times on the IDE, the while loop terminates (which it shouldnt because it doesnt even have an ending condition), and on Putty it crashes with segmentation fault message.

At the point you call the base class, model is uninitialised.
What do you mean that it's not initialised? I thought calling the base class there uses the PC::model variable which is defined
Last edited on
I mean, it's uninitialised!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
$ cat proj.cpp
#include <iostream>
#include <string>
using namespace std;

class Base {
public:
  Base(int n) {
    cout << "base=" << n << endl;
  }
};

class Derived : public Base {
  int model;
public:
  Derived(int _model) : Base(model) {
    model = _model;
    cout << "Derived=" << model << endl;
  }
};

int main()
{
  Derived d(42);
  return 0;
}
$ g++ proj.cpp
$ ./a.out 
base=-1783644528
Derived=42


Base classes are called before you get to anything between the { } in your derived ctor.
HomePC(string _model) : PC(model, "MacOS", 2, 0, 2, 1, 4, 256, 800, 0, 0)
Shouldn't you pass _model to the PC ctor
Yep, I get it now guys. Honestly I never would have noticed that on my own, thank you very much :D
Topic archived. No new replies allowed.