0

I'm learning C++ following this link: https://www.youtube.com/watch?v=mUQZ1qmKlLY. Now I'm confused about member initialization. So, I have three files, main.cpp, Sally.h, Sally.cpp. as the following.
main.cpp

#include <iostream>
#include "Sally.h"

using namespace std;

int main(){
   Sally so(3,87);
   so.print();
}

Sally.h

#ifndef SALLY_H
#define SALLY_H

class Sally
{ 
   public:
       Sally(int a, int b);
       void print();
  private:
       int regVar;
       const int constVar;
};
#endif 

Sally.cpp

#include "Sally.h"
#include <iostream>
using namespace std;

Sally::Sally(int a, int b)
:regVar(a), constVar(b)
{
} 

void Sally::print()
{ cout << "regulat var is: " << regVar << "const var is:" << constVar << endl;
}

When I run the main.cpp file, it does not give me any prints out. Instead, it gives me the following message.

$ g++ main.cpp
/tmp/ccyvg9rV.o: In function `main':
main.cpp:(.text+0x29): undefined reference to `Sally::Sally(int, int)'
main.cpp:(.text+0x35): undefined reference to `Sally::print()'
collect2: error: ld returned 1 exit status

Moreover, why do not I see anything similar to this member initialization in other languages, like Java, Julia or Python?

kkxx
  • 571
  • 1
  • 5
  • 16
  • 3
    That error is nothing to do with member initialization - you just haven't linked `Sally.cpp` with your program. The problem is with your build system, not your code. – Useless Nov 01 '19 at 14:09
  • 1
    As an aside, the reason that Java doesn't have this kind of member initialization, is that Java doesn't care about the overhead of initializing everything twice. C++ gives you a way to avoid the extra work in case you care about it - at the cost of extra complexity. – Useless Nov 01 '19 at 14:10

1 Answers1

2

When I run the main.cpp file

g++ main.cpp

That does not run the file, it compiles and links it.

Since main.cpp is not a full program (you also need Sally.cpp), the linker tells you you have undefined references.

Instead, do:

g++ Sally.cpp main.cpp

And you should get a binary/executable in your current folder that you can run.

Acorn
  • 24,970
  • 5
  • 40
  • 69