Skip to main content
GameDev.net gamedev.net
🔒 Locked

C++ Constructor Question

Started by Ryback Jan 17, 2005 at 9:34 PM 4 replies 1.3k views
Original Post
Ryback
Ryback
Greetings, Sorry if this is too simple of a question. Basically I am trying to understand a PLIB source file. ssgaTeapot is a class inherited from ssgaShape. Now, the constructor is defined as this: ssgaTeapot::ssgaTeapot(int nt):ssgaShape (nt){type=ssgaTypeTeapot();regenerate();} What does this mean exactly? I understand that the body is calling 2 functions. The part I don't exactly get is the ":ssgaShape (nt)" Thanks in advance!
Cloxs
Cloxs
It's an initializer list, normally used to initialize const variables in classes because they cannot be initialized in the body (they're const), and simply sets the variable to whatever is in parenthesis. So for this example ssgaShape is a variable of the class and is being initialized to the int nt.
NoahAdler
NoahAdler
It determines which constructor overload of ssgaShape to use. If it's omitted, it attempts to use the default constructor. If ssgaShape has no default constructor, then it must be explicitly specified as shown. Else how would you specify what gets passed in?

Hope this helps.
-bodisiw
ontheheap
ontheheap
ssgaTeapot::ssgaTeapot(int nt)          :ssgaShape (nt){     type=ssgaTypeTeapot();     regenerate();} 


ssgaTeapot inherits from ssgaShape, and it's just calling ssgaShape's constructor... Is there some other way to look at this?
Ryback
Ryback
Quote:
Original post by NoahAdler
It determines which constructor overload of ssgaShape to use. If it's omitted, it attempts to use the default constructor. If ssgaShape has no default constructor, then it must be explicitly specified as shown. Else how would you specify what gets passed in?

Hope this helps.


So if I define an object of type ssgaTeapot, it will call the constructor of ssgaShape AND the constructor of ssgaTeapot (which is defined in the body)?
NoahAdler
NoahAdler
Quote:
So if I define an object of type ssgaTeapot, it will call the constructor of ssgaShape AND the constructor of ssgaTeapot (which is defined in the body)?


Yep, assuming ssgaTeapot inherits from ssgaShape. For instance the following program:

#include <iostream>struct Base {  Base() { std::cout<<"Base()\n"; }  virtual ~Base() { std::cout<<"~Base()\n"; }};struct Derived : public Base {  Derived() { std::cout<<"Derived()\n"; }  virtual ~Derived() { std::cout<<"~Derived()\n"; }};int main() {  Derived d;}


The output will be
Base()Derived()~Derived()~Base()


This is standard inheritance rules. Base is responsible for initializing its own data, so its constructor needs to be called.
-bodisiw

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.