Declaring and using instances of class

An instance is an object whose description is given by the class. The objects share same methods and attributes, but not same data: each instance may have proper values for each attributes.
You can declare instances of a class in any scope, including inside other classes.

Syntax

classename instancename [ = classename( ...arguments...) ]

In order:
- name of the class
- the identifier of the instance
- and if the constructor has arguments:
- the = symbol
- followed by the list or parameter between parenthesis.

Thus:
classname instancename = classname(arguments) ` or
classname instancename

in the second case, the constructor has no argument.

Examples:

Car mycar = Car(850)
Truck mytruck
Truck mytruck = Truck(10, 25)

 

Using an instance

Once an instance is declared, attributes and methods of the class become visible outside the class providing they are associated with the name of the instance by the dot symbol, with this form:

instanceName.attribute
instanceName.method()

Example of instance
of the Car class:
class Car
  int speed
  int power

  int getSpeed()   return speed
  int getPower()   return power

  void setSpeed(int s)
    speed = s
  return

/class

Car mycar
mycar.setSpeed(150)
print mycar.speed
print mycar.getSpeed()
Displays: > 150
> 150

 Exercises

 

1) The class Buggy is defined below...
class Buggy
 int speed
 int power
 void Buggy(int v, int p)
    speed = v
    ppower = p
 return
/class

Declare an instance named b, with a speed of 100 and a power of 50
Display the attributes.

Answer