Next >>

Forward declarations

What will the following C++ code output? What is happening, and why is our compiler not noting anything particular about our code, even though it does not behave as it should?

main.cpp

#include "my_type.h"

class MyType {
public:
  int a;
  float b;
};

int main() {

  MyType v;
  v.a = 10;
  v.b = 13;

  output(v);

  return 0;
}

my_type.cpp

#include <iostream>

class MyType {
public:
  int a, b;
};


void output(MyType &v) {
  using namespace std;

  cout << "Value: " << v.a << ", " << v.b << endl;
}

my_type.h

#pragma once

class MyType;

void output(MyType &t);

Download files

Answer and comments