Don't understand rare constructor syntax...

Nov 9, 2009 at 8:50am
Hello everyone!
In a project, I'm starting to work with, I have seen a code construct like this:

1
2
3
4
5
6
7
8
9
myclass.h
class myclass {
  public:
  myclass();

  private:
  my_other_class* object1;
  my_other_class* object2;
}

1
2
3
4
5
6
7
8
myclass.cpp

myclass::myclass() 
  :
  object1(0),
  object2(0)
{}


I have no idea (and no idea for what to search), what the syntax after the single colon in the constructor means. Can anybody help me there?

thanks in advance
skulda
Nov 9, 2009 at 9:15am
closed account (z05DSL3A)
See: http://www.cprogramming.com/tutorial/initialization-lists-c++.html
Nov 9, 2009 at 9:20am
It means "contruct object1 with these parameters, and object2 with these parameters". For primitive types (integers, floats, and pointers) there's no difference between that, and just assigning to the variable. It's not the same with some objects, though.
Just to give two examples:
1
2
3
4
5
6
7
8
9
10
11
12
class A{
    int a;
public:
    A(int b):a(b){}
};

class B{
    int a;
public:
    B(){ exit(0); }
    B(int b):a(b){}
};

A doesn't have a constructor that takes no parameters, so if you don't explicitly construct it as above, you'll get a compiler error.
B, on the other hand, has a constructor that takes no parameters, but it messes up the state so bad that it shouldn't be used under most circumstances. In this example, it terminates the program.
Nov 9, 2009 at 11:52am
Ok, thank you, that helped a lot. Now I understand what's happening :)
Topic archived. No new replies allowed.