Class, constructor and inherance.
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Oct 11 22:28:21 PDT 2015
On 10/11/2015 08:26 PM, holo wrote:
> On Monday, 12 October 2015 at 02:30:43 UTC, Meta wrote:
>> On Monday, 12 October 2015 at 02:14:35 UTC, holo wrote:
>>> class credential
>>> {
>>> auto accessKey = environment.get["AWS_ACCESS_KEY"];
>>> auto secretKey = environment.get["AWS_SECRET_KEY"];
>>> }
>>>
>>> class sigv4 : credential
>>> {
>>> private:
>>> const algorithm = "AWS4-HMAC-SHA256";
>>>
>>> auto currentClock = Clock.currTime(UTC());
>>> auto currentDate = cast(Date)currentClock;
>>> auto curDateStr = currentDate.toISOString;
>>> auto currentTime = cast(TimeOfDay)currentClock;
>>> auto curTimeStr = currentTime.toISOString;
>>> auto xamztime = curDateStr ~ "T" ~ curTimeStr ~ "Z";
>>> }
>>
>> You should set these in the constructor rather than in the class body
>> (the only one that's okay to intialize here is `algorithm`, as it's a
>> const string).
>
> I rewrite it to something like this:
What Meta is saying is that the expressions used for default values
class bodies must be known at compile time. For example, you cannot get
current time at run time. Besides, if it did work, there is the question
of "should every sigv4 object get the same default value currentClock,
or should every object get their own time?"
> class credential
> {
> auto accessKey = environment.get["AWS_ACCESS_KEY"];
> auto secretKey = environment.get["AWS_SECRET_KEY"];
> }
As mentioned, that cannot compile.
> class sigv4 : credential
> {
> this(string URI = "/", string queryStr =
> "Action=DescribeInstances&Version=2013-10-15", string headerStr =
> "host:" ~ host ~ "\n" ~ "x-amz-date:" ~ xamztime ~ "\n", string headers
> = "host;x-amz-date")
> {
> auto currentClock = Clock.currTime(UTC());
That is a known error, which is usually caused by copy-paste: Because
you used 'auot' on the left-hand side, that is the definition of a local
variable. 'currentClock' above is not the member of this class. It is
adviced to use fully qualify members with this. in constructors:
this.currentClock = // ...
> auto currentClock = Clock.currTime(UTC());
Just define the members without a default value; they will be
initialized in the constructor:
SysTime currentDate;
> My question was too if now i will inherit that class, will that default
> values be in child class available?
Yes, every variable will obey its default value. When in doubt, test
with simple examples. :)
class Base {
int i = 42;
}
class Derived : Base {
int j;
this() {
this.j = 100;
}
}
void main() {
auto d = new Derived();
assert(d.i == 42); // set by default value
assert(d.j == 100); // set in the constructor
}
Ali
More information about the Digitalmars-d-learn
mailing list