Bug Library Constructor


I don’t understand the behaviour of my arduino for my library :

The most importante code of my library :

#ifndef Dice_h
#define Dice_h

#if ARDUINO < 100
#include <WProgram.h>
#include <Arduino.h>

class Dice {
	Dice(int, int, int);
    void roll();
    void reset();
	int shiftPin, storagePin, dataPin;
	void write(int);

#if ARDUINO < 100
#include <WProgram.h>
#include <Arduino.h>

#include "Dice1.h"
#define WAITIME 20

const int values[] = {0, 1, 2, 3, 6, 7, 14};

void Dice::write(int value) {
	digitalWrite(this->storagePin, LOW);
	shiftOut(this->dataPin, this->shiftPin, MSBFIRST, value);
	digitalWrite(this->storagePin, HIGH);


void Dice::reset() {

Dice::Dice(int shiftPin, int storagePin, int dataPin) {
	this->shiftPin = shiftPin;
	this->storagePin = storagePin;
	this->dataPin = dataPin;

	pinMode(this->shiftPin, OUTPUT);
	pinMode(this->storagePin, OUTPUT);
	pinMode(this->dataPin, OUTPUT);
        this->write(0); // HERE !

void Dice::roll() {
	Dice::write(values[random(1, 7)]);

So my problem is : When i’m calling write(0); or reset(); in the constructor of my Dice class, the program stopped.
(Serial.print in the setup). And when I suppress this line, and call reset in my arduino project, it feels good. Why i can’t call a member function in my constructor please ?

#include <Dice1.h>

int buttonPin = 2;

Dice myDice = Dice(12, 10, 11);

void setup() {
  pinMode(buttonPin, INPUT);

void loop() {
  if(digitalRead(buttonPin) == HIGH) {

Thank you !

Because "this" does not point to the object at this stage.


Constructors get run before the hardware gets initialized. So things like digitalWrite and shift-out and stuff like that often just won't work. A constructor shouldn't be trying to execute any code that relies on the hardware. It should just be doing things like setting initial values for variables or stuff like that. Make a begin() or init() method that you can call in setup, like how Serial works.