How to initialize a struct, which you need for a function as parameter, in the function signatur

Hi everyone,

im wondering if there is something similar to java in c++ to create/initialize an object within a method signatur

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//in java im used to things like this
public Detailclass{
  String name;
  int amount;
  //parameterized constructor
  public Detailclass(String name,int amount){
  this.name=name;
  this.amount=amount;
}

public class Main{

 public static void doSometing(String whatever,int anumber,Detailclass something){
 //some code
 }
public static void main(String args[]){

 //i  could call the method like this
 doSomething("hello",3,new Detailclass("hi",4));//is there some way to pass a to be constructed object as parameter in c++ ?
//i dont want to define that struct needed one line above, i want it to be created right in the functions signatur, that needs it as parameter


}//end main
}//end main class 


Thanks in advance :)
Last edited on
I don't do Java, but do you mean something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

using namespace std;

struct test
{
    int i;
    int j;
};

void testFunct(test tst)
{
    cout << tst.i << " " << tst.j << endl;

}

int main()
{
    testFunct({1,2});

    return 0;
}

It wasn't exactly what i'm looking for but i guess i answered the question myself with your help. I guess there is no such thing in C++, if there was, one wouldnt know how to free that memory, since the object would be created while passing to a function.

Thanks anyway.
If you must pass dynamically allocated objects you should consider using smart pointers like std::unique_ptr.

1
2
3
4
void doSomething(const std::string& str, int n, std::unique_ptr<Detailclass> dp)
{
	// ...
}

Then you can allocate the object at the same time you call the function without having to worry about leaking.

 
doSomething("hello", 3, std::unique_ptr<Detailclass>(new Detailclass("hi", 4)));

In C++14 you can make it even shorter.

 
doSomething("hello", 3, std::make_unique<Detailclass>("hi", 4));

http://en.cppreference.com/w/cpp/memory/unique_ptr
Last edited on
Thanks, that was exactly what i'm looking for ! : D
Topic archived. No new replies allowed.