inheriting a default value (short and to the point)

Dec 2, 2009 at 12:48am
So my class Polygon has a member:
 
int Polygon::default_length (1);


anyway I want my class Rectangle which is derived from Polygon to inherit that member; however, I can tell it doesn't, because my output is off.

I have a constructor for Rectangle defined as this:
1
2
3
4
5
Rectangle::Rectangle (int length, int width)
{
	this->length = length ? length: default_length;
	this->width = width ? width: default_width;
}


However, in my main function when I execute the code:
1
2
	Rectangle rect;
	rect.area ();


my output is this:

The area of this rectangle is -1881144128.

My default_width value is 1 so I should get 1 * 1 which is 1 not -1881144128. So my program must be giving it some random number in memory for length. Why isn't Rectangle inheriting the default_length value from polygon?
Here is Rectangle::area ():
1
2
3
4
void Rectangle::area()
{
	cout << "The area of this rectangle is " << length * width << "." << endl;
}

Last edited on Dec 2, 2009 at 2:32am
Dec 2, 2009 at 2:37am
You are calling the default constructor of rectangle, which doesn't initialize anything, not your custom constructor.
Dec 2, 2009 at 2:40am
I have only one constructor:
1
2
//Rectangle.h
Rectangle (int length=0, int width=0);


So this constructor would be called if my main function statement is:
 
Rectangle rect;


Right?
Maybe it would help if I showed you how I define default_length in Polygon.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*
 *  Polygon.cpp
 *  
 *
 *  Created by Matthew Dunson on 11/30/09.
 *  Copyright 2009 The Ohio State University. All rights reserved.
 *
 */

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

int Polygon::default_length (1);

Last edited on Dec 2, 2009 at 2:52am
Dec 2, 2009 at 4:11am
Hey... wait a minute.... didn't I just answer this?

http://cplusplus.com/forum/general/16959/
Topic archived. No new replies allowed.