Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instantiation in c++

Tags:

c++

object

oop

First of all, I would like to notify you, I have definetly searched for answers about my following question, but im a complete newbie to C++.

I am coming from the luxurious life of C# and Java, now trying to pick up a thing or two about c++

The question is about instantiation.

I use code::block as my IDE of choice.

Currently I am just playing around with what in C# (which I'm actually quite familiar with and have written several applications in) is

2 classes

the class containing main and Person

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


using Models.Person;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
           Person person = new Person();
           Console.WriteLine(person.getName());
        }
    }
}

and the person class:

namespace ConsoleApplication1
{
   public class Person{
       private string name = "Bob";

       public string getName(){
           return name;
       }
   }
}

(dont mind bad or right written syntax, its just to simulate what i want to achieve)

I want to achieve the same in C++

I have looked up, and learned about headers to some extent, and picked up a bit of the syntax. This is what I have right now.

main.cpp

#include <iostream>
using namespace std;

int main()
{
   Person person;
   cout << person->getName() << endl;
}

Person.h

#ifndef PERSON_H
#define PERSON_H

#include <string>

class Person
{
    public:
        Person();
        virtual ~Person();
        std::string getName();
    protected:
    private:
};

#endif // PERSON_H

player.cpp

#include "Person.h"
#include <string>

using std::string;

Person::Person()
{
    //ctor
}

Person::~Person()
{
}

string Person::getName()
{
    return name;
}

Considering the above code, I have multiple questions.

I never found a good source that showed me whether I should instantiate using Person person; or Person person = new Person();

Which one of the two is the one I'm supposed to use?

And another question I'm dying for is, do I define class members in the header file or in the class file?

Currently I'm recieving the following errors:

'person' was not declared in scope and expected ';' before person

I'm not nescesarily asking you to resolve my errors, I'll manage that upon recieving answers on my questions.

like image 635
Joey Roosing Avatar asked Mar 21 '11 15:03

Joey Roosing


People also ask

What is instantiation with example?

When you provide a specific example to illustrate an idea, you instantiate it. You say you believe in unicorns, but so far you haven't been able to instantiate that belief.

What do you mean by instantiation?

noun. the act or an instance of instantiating. the representation of (an abstraction) by a concrete example. logic. the process of deriving an individual statement from a general one by replacing the variable with a name or other referring expression.

What is instantiation in C Plus Plus?

Instantiation is when a new instance of the class is created (an object). In C++ when an class is instantiated memory is allocated for the object and the classes constructor is run. In C++ we can instantiate objects in two ways, on the stack as a variable declaration, or on the heap with the new keyword.

What is instantiation in C sharp?

The process of creating an object from a class is called instantiation because an object is an instance of a class. Now that you have defined a new class type, it is time to instantiate an object of that type. Mimicking its predecessors, C# uses the new keyword to instantiate an object (see Listing 5.3).


1 Answers

As larsmans said, Person person and Person *person = new Person() are result in the new Person instance being allocated in the stack/heap respectively.

What this means for you (and this is the answer to the "which should I use?" question) is that in the first case, the memory for the object is managed automatically (that's the good news). The bad news is that the lifetime of the object is also managed automatically, and you don't have any control over it. As soon as the person variable goes out of scope, the object is destroyed. Period.

In the second case (new), the object's lifetime is managed by you (it will exist until you do delete person). The bad news here is that the memory is also managed by you: if you don't ever do delete person, the memory allocated to that object will leak. It won't make any difference if you have no reference to person anywhere in scope anymore.

So if the lifetime is long enough for you, don't use a pointer. Otherwise, you will have to.

For class members:

  • They have to be declared in the header file; if you don't declare them and try to use them, you will get a compiler error.
  • They may optionally be defined in the header file; if not, you can define them in the .cpp file; if you don't define them anywhere and try to use them, you will get a linker error.

Generally definitions should go to the .cpp file, but it's OK if you define really short methods in the header.

Addendum

Of course there are plenty of details I didn't touch upon in this short answer. Here's a few important ones you might want to look into:

  • Using new/delete to manage memory can also give birth to lots of other problems apart from memory leaks; dangling pointers (which point to memory that has been released, and therefore cannot be used anymore -- this is essentially the "reverse" error than a memory leak) is probably #2 on the list.
  • Using some kind of smart pointer will help in achieving "C# semantics": whenever the last smart pointer to some memory goes out of scope, the memory will be released automatically on the spot (if it points to an object the destructor will run at this time; this is called deterministic destruction, C# does not have it and it has to try to emulate it with IDisposable). There are very good and mature smart pointers you can use in C++0x and Boost.
  • In C++, all types work like C# value types. If a takes up 2MB of memory and you do b = a, you just had the compiler populate a brand new 2MB of memory with a copy of a (and probably do a lot of extra work to achieve that). If that is not your intention, you need to store a pointer or a reference to a instead.
like image 191
Jon Avatar answered Sep 28 '22 16:09

Jon