Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are these C++ terms correct? [closed]

Tags:

c++

I'm reading a book, the Primer guide to C++.

I think I got the hang of it upto a point, I just want to clarify a few things.

  1. It says that a class is like a data type (A data type being int, char, ect ..) and that an Object/Instance is like a variable. Is this true?

  2. What is a data form?

  3. What part of a statement is the declaration? Is it the data type + the variable, and the = is the assignment?

like image 316
Ayfiaru Avatar asked May 24 '12 19:05

Ayfiaru


1 Answers

Not quite.

A class is "like a data type" in the sense that it's a template for the creation of an object, but it isn't itself an object that you can use.

When you use that template to create an instance of an object, then you can make use of that object. You may create as many instances as you want - you can think of those instances as variables.

For example:

class Person
{
    public:
        Person() : name("Joe Bloggs") {}

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

        void setName(std::string n) { name = n; }

    private:
        std::string name;    
};

This is a class definition for a Person. It is not a variable. You cannot call setName on it because it doens't exist yet. But when you do:

int main()
{
    Person p, q;
    p.setName("Jill Bloggs");
    q.setName("Bob King");
    std::cout << p.getName() << " " << q.getName() << std::endl;
}

You created two instances of people that you can assign to, change, and use - they are variables called instances.

I have no idea what "data form" means, ignore that.

As for declaration - the declaration states that an instance of something will be present. For example, if you were creating a class, and your header file had:

class foo
{
    public:

        foo(int value);

        void bar();

    private:
        int x;
};

You are declaring that you have a function called bar that returns void and that you have an integer called x.

No memory is allocated for the variable, x, and no definition is provided or bar, so they're just declarations. Your source file would probably provide definition for bar like:

void foo::bar()
{
    //some code
}

and a constructor definiton for foo that would initialize x with a value and control how it was created (with an initializer list):

foo::foo(int value) : x(value)
{
    //some code
}
like image 86
John Humphreys Avatar answered Sep 23 '22 21:09

John Humphreys