Thread: Simple question on derived classes

  1. #1
    Registered User
    Join Date
    Feb 2017
    Posts
    14

    Simple question on derived classes

    Hi all,

    I have a derived a class 'box' from my base class 'rectangle'. My main problem is getting my constructor for box to work. My IDE complains that "No default constructor exists for class "rectangle"".

    Code:
    class box : public rectangle
    {
    private:
    	double height;
    public:
    	box(double height_val)
    	{
    		height = height_val;
    	}
    I've tried passing a parameter to my base class 'rectangle' (red highlight):

    Code:
    class box : public rectangle
    {
    private:
    	double height;
    public:
    	box(double height_val) : rectangle(height_val)
    After doing that it gives a syntax error with "+2 overloads". My base constructor rectangle looks like this:

    Code:
    rectangle(double length_val, double width_val)
    What am I doing wrong?

    Thanks for your help in advance.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Either use a default parameter value for width, or pass 2 parameters.
    Code:
    #include <iostream>
    #include <iomanip>
    using namespace std;
    
    class Rectangle {
      double height, width;
    public:
      Rectangle(double h, double w ) {
        height = h;
        width = w;
      }
    };
    
    class Box : public Rectangle {
      private:
        double height;
    public:
        Box(double height_val) : Rectangle(height_val,height_val)
        {
            height = height_val;
        }
    };
    
    int main ( ) {
      Box box(2);
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Conversions between base classes and derived classes
    By tharnier in forum C++ Programming
    Replies: 14
    Last Post: 03-18-2011, 10:50 AM
  2. Derived classes, please help
    By Mikey_S in forum C++ Programming
    Replies: 6
    Last Post: 03-01-2009, 02:41 PM
  3. Simple Question about Classes
    By Loctan in forum C++ Programming
    Replies: 5
    Last Post: 06-26-2006, 02:40 AM
  4. Help accessing classes and derived classes
    By hobbes67 in forum C++ Programming
    Replies: 8
    Last Post: 07-14-2005, 02:46 PM
  5. Simple yes/no question regarding classes
    By Ricochet in forum C++ Programming
    Replies: 5
    Last Post: 12-11-2003, 05:06 PM

Tags for this Thread