2 Replies - 561 Views - Last Post: 06 August 2009 - 08:31 PM Rate Topic: -----

#1 Flipside  Icon User is offline

  • D.I.C Head

Reputation: 12
  • View blog
  • Posts: 70
  • Joined: 03-July 09

New to C++: Creating Instances / Passing Them

Post icon  Posted 06 August 2009 - 07:42 PM

Hi, I'm new to C++ and I'm having troubles creating an instance of a class and then passing it.

I have a class called Sphere, and within it I have different attributes (actually just one at the time).

Sphere.cpp:
#include "sphere.h"

Sphere::Sphere(double arg_r) {
	radius = arg_r;  //Radius is defined in sphere.h as a double
}


In my main class, I want to create a new "sphere". (Not sure if this is even right).

Then I want to pass this instance of Sphere to ExampleClass.

Main.cpp:
int main(int argc, char* argv[]) {
	Sphere sphere = Sphere(1.0);

	ExampleClass ex = ExampleClass(sphere);

	return 0;
}


ExampleClass.cpp:
#include "exampleclass.h"
#include "sphere.h"

ExampleClass::ExampleClass(Sphere s) {
   // Some code that will use Sphere s
}



I've tried doing this (or variations close to this) and haven't had any success. I was hoping someone couldn't straighten things out for me.

Is This A Good Question/Topic? 0
  • +

Replies To: New to C++: Creating Instances / Passing Them

#2 eker676  Icon User is offline

  • Software Engineer
  • member icon

Reputation: 378
  • View blog
  • Posts: 1,833
  • Joined: 18-April 09

Re: New to C++: Creating Instances / Passing Them

Posted 06 August 2009 - 07:47 PM

Try making the sphere a reference in ExampleClass::ExampleClass(Sphere s)

Like this:

ExampleClass::ExampleClass(Sphere& s);

Then it doesn't call the copy constructor from the Sphere class.
Was This Post Helpful? 1
  • +
  • -

#3 Flipside  Icon User is offline

  • D.I.C Head

Reputation: 12
  • View blog
  • Posts: 70
  • Joined: 03-July 09

Re: New to C++: Creating Instances / Passing Them

Posted 06 August 2009 - 08:31 PM

View Posteker676, on 6 Aug, 2009 - 06:47 PM, said:

Try making the sphere a reference in ExampleClass::ExampleClass(Sphere s)

Like this:

ExampleClass::ExampleClass(Sphere& s);

Then it doesn't call the copy constructor from the Sphere class.

Thanks, I'm fighting with some other stuff right now so I can't say how it went yet.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1