0

I have a relatively simple C++ code. It compiles, but after starting it displays the message "Process terminated with status -1073741510 (0 minute (s), 13 second (s))". Is the code normal or is there some logical error? If it's normal, what should be displayed and why?

#include <iоstrеаm> 
#include <string>  
struct А { 
  А(std::string) {} 
}; 

struct В : public А { 
  В() : А ( s = f() ) {} 
  void print() { std::cout << s << std::еndl; } 
  std::string f() { return "Hello"; } 
private: 
  std::string s; 
}; 

int main() { 
  В b; 
  b.print(); 
  rеturn 0; 
}
litstal
  • 1
  • 2
  • 2
    "Globally speaking, Exit Code 0xC000013A means that the application terminated as a result of a CTRL+C or closing command prompt window" https://stackoverflow.com/a/46610564/10686048 – ChrisMM Oct 10 '19 at 08:32
  • 3
    @litstal The program has undefined behavior. In this argument expression A ( s = f() ) the object s is not yet constructed. – Vlad from Moscow Oct 10 '19 at 08:32

1 Answers1

-1

The culprit is

A ( s = f() )

where you are accessing s before B is constructed. And, as rafix07 points out, f as well. That's undefined behavior and that exit code tells you you did something wrong (memory access violation etc). Apart from that, it looks a bit strange and not too easy to read and I am not sure what you are trying to do (which is a problem by itself, code should try to epxress the intent as clearly as possible): do you just want to initialize A with what f returns, or do you want to do that and make s have the same value, or something else? In any case, you can use A( f() ) and s( f() ) for instance, if that is your intent:

struct B : public A { 
  B() :
    A( f() ),
    s( f() )
  {}

  static std::string f() { return "Hello"; }
};

Note I did make f static to make sure it can be used before A is initialized.

stijn
  • 34,664
  • 13
  • 111
  • 163
  • 1
    What about this quote *Member functions (including virtual member functions) can be called from member initializers, but the behavior is undefined if not all direct bases are initialized at that point.* [from reference](https://en.cppreference.com/w/cpp/language/initializer_list). You are calling `f` before `A` is constructed - `A(f())`. – rafix07 Oct 10 '19 at 08:39
  • @rafix07 fair point - I always thought the rule was 'ok as long as it doesn't refer to member variables' or so, which practically might be the case, but looks like I'm wrong so I'll change the answer. – stijn Oct 10 '19 at 08:45
  • See also: https://stackoverflow.com/questions/11174129/can-member-functions-be-used-to-initialize-member-variables-in-an-initialization – stijn Oct 10 '19 at 08:49