instantiating a class in another class

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • madshov
    New Member
    • Feb 2008
    • 20

    instantiating a class in another class

    Hi,
    I have made a matrix class, that I wish to make an instiation of in another class.
    Matrix class:
    Code:
    #include <vector>
    #include <iostream>
    
    using namespace std; // So the program can see cout and endl
    
    class Matrix
    {
    
       //-public member data
       public:
         //-constructor, copy constructor, and deconstructor
         Matrix(const vector< vector<double> > &m);
         Matrix(const Matrix& m);
         ~Matrix();
    
         //-getter methods
         int get_rows() const;
         int get_cols() const;
         double &value(int row, int col);
    
      //-private member data
      private:
         vector< vector<double> > mat;
         int columns;
         int rows;
    };
    /**Constructor*/
    Matrix::Matrix(const vector< vector<double> > &m)
    :mat(m),rows(m.size()),columns(m[0].size())
    {
    }
    /**Copy Constructor*/
    Matrix::Matrix(const Matrix& m)
    {
    }
    /**Deconstructor*/
    Matrix::~Matrix()
    {
    }
    second class:
    Code:
    class test
    {
    	int length;
    	double val;
            vector< vector<double> > vect_2d;
            Matrix mat_one;
        
    	public:
            //constructor
    	test(const int l, Angles angles);
    	
            //copy
    	test(const test &s);
    	
            //destructor
    	~test();
    	
    	void print();
    };
    
    test::test(const int l, Angles angles)
    {
         vector< vector<double> > vect_2d(3, vector<double>(3,1));  	
    
         Matrix mat_one(vect_2d);
    }
    
    test::~test()
    {
    }
    
    void test::print()
    {
          mat_one.value(1,1);
    }
    I not able to declare mat_one in the test class, because there is no matching function in the matrix class. But I can't write something like Matrix mat_one(vector< vector<double> >). Any hints? Thanks.
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    You need to either, provide Matrix with a default constructor or when you construct you test class specifically call one of the Matrix constructors that are available.

    I will assume you know how to provide Matrix with a default constructor.

    You can call a specific constructor for a nested class in the same way that you initialise a variable in class constructor, like this

    [code=cpp]
    test::test(cons t int l, Angles angles)
    : mat_one( vector< vector<double> >(3, vector<double>( 3,1)))
    {
    }
    [/code]

    This is rather complex, you may wish to consider writing a constructor for Matrix that takes the same parameters as test.

    Comment

    Working...