c++ Grammar Questions

Asked 2 years ago, Updated 2 years ago, 18 views

Hi, everyone What's the mechanism or grammar for the next code to work? The testFunc() function receives object D as a factor, and it works even if you insert object C pointer.

#include <iostream>

class C
{
public:
  C (){}
};

struct D
{
protected:
  C *node_{nullptr};
public:
  D() = default;
  D(C *c) { node_ = c;};

};

void testFunc(D input){
  std::cout << "Hello, World!" << std::endl;
}
int main() {
  C* c = new C();
  testFunc(c);

  return 0;
}

c++

2022-09-20 21:54

1 Answers

Because the D class has a constructor named D:D(C*), an instance of D is created to receive C* and the function is called.

This constructor allows the following code:

D d = new C;

These constructors are called conversion constructors because they appear to convert to different types.

Use explicit to prevent this implicit generation.

explicit D(C *c) { node_ = c;}


2022-09-20 21:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.