473,395 Members | 2,446 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

How to pass objects to constructor?

Hi,

I am a Java developper, and now I'm trying to learn C++. I'm very new to the programming language. I'm trying to pass objects to a constructor, which I appear to be doing wrong.

A triangle-object needs to contain references to 3 "Vertex" objects, which are the points of the triangle.

Triangle.h
Expand|Select|Wrap|Line Numbers
  1. #ifndef TRIANGLE_H_
  2. #define TRIANGLE_H_
  3.  
  4. #include "Vertex.h"
  5.  
  6. namespace geometry {
  7.  
  8.     class Triangle {
  9.         public:
  10.             Vertex v1,v2,v3;
  11.  
  12.             Triangle(Vertex & one, Vertex & two, Vertex & three);
  13.             virtual ~Triangle();
  14.         };
  15.  
  16.     }
  17.  
  18. #endif /* TRIANGLE_H_ */
Triangle.cpp
Expand|Select|Wrap|Line Numbers
  1. ...
  2. Triangle::Triangle(Vertex & one, Vertex & two, Vertex & three) {
  3.         v1 = one;
  4.         v2 = two;
  5.         v3 = three;
  6.     }
  7. ...
  8.  
Vertex.h
Expand|Select|Wrap|Line Numbers
  1. #ifndef VERTEX_H_
  2. #define VERTEX_H_
  3.  
  4. #include "../algebra/Vector4f.h"
  5. #include "../algebra/Matrix4f.h"
  6. using namespace algebra;
  7.  
  8. namespace geometry {
  9.  
  10.     class Vertex {
  11.         public:
  12.             Vector4f position;
  13.  
  14.             Vertex(float x, float y, float z);
  15.  
  16.             float x();
  17.             float y();
  18.             float z();
  19.  
  20.             void transform(Matrix4f& m);
  21.  
  22.             virtual ~Vertex();
  23.     };
  24.  
  25. }
  26.  
  27. #endif /* VERTEX_H_ */
The above code generates the error "Triangle.cpp:13:63: error: no matching function for call to 'geometry::Vertex::Vertex()' note: candidates are: geometry::Vertex::Vertex(float, float, float)",

among others.
My interpretation is that C++ tries to create the vertex-objects in the call to Triangle::Triangle(Vertex & one, Vertex & two, Vertex & three) with only this code, whereas I simply want to have one, two and three as placeholders for passed objects when I'm actually using the constructor, like I would have in java.

As you can see, I am an absolute beginner at C++.
What am I doing wrong?

Thanks
Feb 6 '11 #1

✓ answered by newb16

use constructor initializers list:
Triangle::Triangle(Vertex & one, Vertex & two, Vertex & three) {
: v1(one)
, v2(two)
{
// the rest of constructor
..

11 17376
horace1
1,510 Expert 1GB
it is saying that line 2 of triangle.cpp
Expand|Select|Wrap|Line Numbers
  1. Triangle::Triangle(Vertex  &one, Vertex  &two, Vertex  &three) {
  2.  
requires a default constructor for Vertex, e.g.
Expand|Select|Wrap|Line Numbers
  1.             Vertex() {};
  2.  
Feb 6 '11 #2
I know, but I can't see why. What I'm trying to do there is creating a constructor for a Triangle that takes three Vertex-objects as parameters. I really don't see how having a default constructor for a vertex is relevant.

I choose to only provide a constructor for a Vertex that takes x,y,z - coordinates. The constructor for a Triangle has no concern in this, it should just accept whatever three vertex-objects I give it when I use it, regardless of the constructor used to create the vertex-objects.

So why doesn't it just do that? Why do I need a default constructor? I just want to pass objects by reference
Feb 6 '11 #3
newb16
687 512MB
use constructor initializers list:
Triangle::Triangle(Vertex & one, Vertex & two, Vertex & three) {
: v1(one)
, v2(two)
{
// the rest of constructor
..
Feb 7 '11 #4
Savage
1,764 Expert 1GB
If you write your own constructor the built-in default constructor seizes to exist, so you will have to write it(the default constructor) by yourself.

Regards,
Savage
Feb 9 '11 #5
yes savage, I realise that. I just don't get why C++ forces me to have a default constructor, even when I only wanted parametrized constructors. Anyway, newb16's paramater list did to the trick. No default constructor needed.
Feb 9 '11 #6
Savage
1,764 Expert 1GB
Because vertices contained in Triangle class are real objects and not references, and therefore they need to be constructed. Since initializer list runs "before" constructor, the problem can be solved in this way since the list uses the inbuilt assingment operator .. but what if later on you want to return a Vector by value from some function? Like this:

Expand|Select|Wrap|Line Numbers
  1. Vector generateRandomVector()
  2.         {
  3.             //generate random vector
  4.             return  rndVector;
  5.         }
  6.  
, when this function returns it will put its return value on the stack frame by using the default constructor.. only problem is that default constructor has been suppressed by yours assignment constructor and the code wont compile giving you a simmiliar error message as it did before you solved it using initializer's list. ^^

So if you plan having some function like those above, either write the default constructor, or assign default values to your assignment constructor.

Regards,
Savage
Feb 9 '11 #7
I see, thank you.

I'm guessing my best option will be to just store references or pointers instead of the objects, since I would like to share vertices between triangles.

Another question; in the context of randomVertex-function you described:

Is it possible to return a pointer to an object created in the body of the function like so?
Expand|Select|Wrap|Line Numbers
  1. Vertex* generateRandomVertex()
  2. {
  3.    //generate random x,y,z-values
  4.    Vertex v(x,y,z);
  5.    Vertex* pointer = &v;
  6.    return  pointer;
  7. }
Or would the 'local' object in the body be deconstructed after the return? C++ pointers and memory-management are pretty confusing for me :p
Feb 9 '11 #8
Savage
1,764 Expert 1GB
You can, but you need to create the object on the heap and not on the stack like you did here since after function call all local variables of the function get wiped out, so you would return a pointer to some garbage.

Write it like this instead:

Expand|Select|Wrap|Line Numbers
  1. Vertex* generateRandomVertex()
  2. {
  3.    //generate random x,y,z-values
  4.    Vertex* pointer = new Vertex(x,y,z);
  5.    return  pointer;
  6. }
or even better like this:

Expand|Select|Wrap|Line Numbers
  1. Vertex* generateRandomVertex()
  2. {
  3.    //generate random x,y,z-values
  4.    return new Vector(x,y,z);
  5. }
, but if you want to use pointer to do this then remember that C++ doesnt have garbage collector and that you will have to free the memory by yourself by using delete. Also if you want to share references between instances of triangle note that reference class members must be initialized in the constructors initializer list and ofc, once initialized they cant be reset to reffer to some other object of their type.

Regards,
Savage
Feb 9 '11 #9
"if you want to share references between instances of triangle note that reference class members must be initialized in the constructors initializer list and ofc, once initialized they cant be reset to reffer to some other object of their type."

Could you elaborate? I just now rewrote the header like this to allow the sharing of vertices. Is it correct?

Expand|Select|Wrap|Line Numbers
  1. class Triangle: public rendering::HitAble {
  2.     public:
  3.     Vertex* v1,v2,v3;
  4.  
  5.     Triangle(): v1(one), v2(two), v3(three){};
  6.         ...other stuff
  7.  
Thanks for the help.
Feb 9 '11 #10
Savage
1,764 Expert 1GB
If you are going to use pointers then this is fine if one,two,three are pointers as well to a Vertex.. if they are still references then you need to use address-of operator(&) infront of one,two and three to properly initialize v1,v2,v3 pointers(or change the constructor to accept pointers instead of references) If what you are building is some small project you'll be fine by doing like this, if its going to be something bigger those reference sharings can really become a headache, so you might want to use handler class which track how many references are there to a single object. Here is a solid example of how to use them.

Regards,
Savage
Feb 9 '11 #11
Thanks, I'll look into it.
I appreciate the help
Feb 9 '11 #12

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: lawrence | last post by:
I've read that objects should always be passed by reference to other objects. I've also read that future versions of PHP may not support runtime passing by reference (default passing by reference...
6
by: Bryan Martin | last post by:
I have a object that is created in a seperate domain which needs to be passed back to the parent class. Because this object is created in a seperate domain if I try to pass the object back to the...
5
by: Andy | last post by:
Hi Could someone clarify for me the method parameter passing concept? As I understand it, if you pass a variable without the "ref" syntax then it gets passed as a copy. If you pass a...
6
by: Garma | last post by:
According to what I have learnt so far, instantiating global objects should be the last resort. Is there any reasons why so? Sometimes some objects or their pointers have to be shared among...
5
by: twizansky | last post by:
Hello, I have a problem with values of object properties changing seemingly on their own. I am completeley baffled and would appreciate any assistance. specifically, I have a class called...
2
by: Barry Moon | last post by:
Hi Can anyone give me any help with passing an object across processes, via drag and drop? I've written a custom ListView control, which supports dragging and dropping of its items. The...
0
by: hawklord451 | last post by:
To get a foot hold in the area of web services I have created the following small project. I have created a group of classes to describe a overall Request class. the Request Class is made from a...
2
by: Witold Iwaniec via .NET 247 | last post by:
It seems that when you pass an object to a function it is always passed by reference even if it is explicitly declared ByVal. Is it the behavior of VB.Net? Here is sample code from sample Asp.Net...
4
by: Deckarep | last post by:
Hello fellow C# programmers, This question is more about general practice and convention so here goes: I got into a discussion with a co-worker who insisted that as a general practice all...
1
by: Ilyas | last post by:
Hi all What are the best practises for passing custom objects to and from from services? In particular: 1)Should datasets be passed, or custom objects be passed? 2)When it comes to passing...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.