开发者

Creation of an object in C++

开发者 https://www.devze.com 2022-12-26 19:09 出处:网络
Isn\'t A a = new A();// A is a class name supposed to work in C++? I am getting: conversion from \'A*\' to non-scalar

Isn't

 A a = new A();   // A is a class name

supposed to work in C++?

I am getting:

conversion from 'A*' to non-scalar type 'A' requested

What开发者_Go百科s wrong with that line of code?


This works in Java, right?

Also, what is the correct way to create a new object of type A in C++, then?


No, it isn't. The new operation returns a pointer to the newly created object, so you need:

A * a = new A();

You will also need to manage the deletion of the object somewhere else in your code:

delete a;

However, unlike Java, there is normally no need to create objects dynamically in C++, and whenever possible you should avoid doing so. Instead of the above, you could simply say:

A a;

and the compiler will manage the object lifetime for you.

This is extremely basic stuff. Which C++ text book are you using which doesn't cover it?


new A() returns a pointer A*. You can write

A a = A();

which creates a temporary instance with the default constructor and then calls the copy constructor for a or even better:

A a;

which just creates a with the default constructor. Or, if you want a pointer, you can write

A* a = new A();

which allows you more flexibility but more responsibility.


The keyword new is used when you want to instantiate a pointer to an object:

A* a = new A();

It gets allocated onto the heap.. while when you don't have a pointer but just a real object you use simply

A a;

This declares the object and instantiate it onto the stack (so it will be alive just inside the call)


You need A* a= new A();

new A(); creates and constructs an object of type A and puts it on the heap. It returns a pointer of that type.

In other words new returns the address of where the object was put on the heap, and A* is a type that holds an address for an object of type A

Anytime you use the heap with new you need to call an associated delete on the address.


new gets you a pointer to the created object, therefore:

A *a = new A();


First, new returns a pointer, so you need to declare the a's type as 'A*'. Second, unlike Java, you don't need parenthesis after A:

A* a = new A;

0

精彩评论

暂无评论...
验证码 换一张
取 消